Search code examples
javascriptfirefoxsvghtml5-canvasbase64

Firefox error rendering an SVG image to HTML5 canvas with drawImage


I am trying to convert an external svg icon to a base64 png using a canvas. It is working in all browsers except Firefox, which throws an error "NS_ERROR_NOT_AVAILABLE".

var img = new Image();
img.src = "icon.svg";

img.onload = function() {
    var canvas = document.createElement("canvas");              
    canvas.width = this.width;
    canvas.height = this.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(this, 0, 0);
    var dataURL = canvas.toDataURL("image/png");
    return dataURL;
};

Can anyone help me on this please? Thanks in advance.


Solution

  • Firefox should draw this SVG to canvas without problems these days.

    Firefox used to only support drawing SVG images to canvas when the svg file had width/height attributes on the root <svg> element and those width/height attributes were not percentages. That bug was fixed some time ago though.