Firefox error rendering an SVG image to HTML5 canv

2020-01-27 08:42发布

问题:

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.

回答1:

Firefox does not support drawing SVG images to canvas unless the svg file has width/height attributes on the root <svg> element and those width/height attributes are not percentages. This is a longstanding bug.

You will need to edit the icon.svg file so it meets the above criteria.