Firefox : canvas.toDataURL in image.onload but returning transparent image

前端 未结 1 1894
情书的邮戳
情书的邮戳 2021-01-29 03:06

I know that the image must be complete, its loading finished before using the toDataURL function on the canvas, put the code in the image.onload function ensures that.

A

相关标签:
1条回答
  • 2021-01-29 03:23

    You need to set absolute width and height attributes to your root svg node (e.g in px).
    The default is 100% but FF has no way to know relative to what (specs don't say yet). ` Chrome makes it relative to something that only they know.

    So FF won't draw your svg image, on the canvas, but won't fire an error either, since the image has loaded correctly (in an html document, they could know what the dimensions should be relative to).

    var xmlSource = '<svg xmlns="http://www.w3.org/2000/svg" width="45" height="45" viewBox="0 0 54.4 54.4"><g><circle cx="27.2" cy="27.2" r="21.2" stroke-width="3" stroke="#606060" style="fill: rgb(189, 189, 189);"/><text dx="26" dy="34" text-anchor="middle" style="font-size:18px; fill: #000000; font-family: Arial, Verdana; font-weight: bold">90</text></g></svg>';
    function callback(dataURI){
      var img = new Image();
      img.src = dataURI;
      document.body.appendChild(img);
      console.log(dataURI);
      }
    var imageWidth = imageHeight = 45;
    var image = new Image();
    
    image.onload = (function (imageWidth, imageHeight) {
        var canvas = document.createElement('canvas');
        canvas.width = imageWidth;
        canvas.height = imageHeight;
        
        var context = canvas.getContext('2d', {preserveDrawingBuffer : true});
        context.drawImage(image, 0, 0, imageWidth, imageHeight);
    
        var dataURL;
        dataURL = canvas.toDataURL("image/png");
    
        callback(dataURL);
    
    }).bind(this, imageWidth, imageHeight);
    
    image.onerror =
    image.onabort = function () {
        console.error("generateIcon : error on image");
    }
    
    image.src = 'data:image/svg+xml;base64,' + btoa(encodeURIComponent(xmlSource).replace(/%([0-9A-F]{2})/g, function (match, p1) {
                return String.fromCharCode('0x' + p1);
            }));

    0 讨论(0)
提交回复
热议问题