Problems calling drawImage() with svg on a canvas context object in Firefox
Asked Answered
T

1

6

I basically want to transform my SVG into a PNG image. So I turn the SVG into an SVG image and try to draw that on a canvas to be able to get it as a PNG via the toDataURL() method. This works fine in Chrome, but in Firefox it produces a very uninformative error: NS_ERROR_NOT_AVAILABLE

After searching and experimenting a bit, I tried a different SVG source and all of a sudden everything worked fine. Any ideas what could cause the method to work fine for the first SVG string but fail for the second one? How can I change my SVG so that it will work?

Fiddle: http://jsfiddle.net/3AXwb/

var image = new Image();
image.src = 'data:image/svg+xml,' + escape(xml);
image.onload = function () {
    var canvas = document.createElement('canvas');
    canvas.width = image.width;
    canvas.height = image.height;
    var context = canvas.getContext('2d');
    document.getElementById('container').appendChild(canvas);
    context.drawImage(image, 0, 0);
}
Thrower answered 7/5, 2014 at 10:13 Comment(0)
B
18

Add a width attribute to the outer <svg> element. E.g. width="450"

The first case has width and height, the second only height and Firefox currently required both width and height to be present.

Bobsled answered 7/5, 2014 at 11:5 Comment(1)
No freakn way... :D Thank you very much! I searched for hours and in the end it's a stupid width property... You saved me some more valuable time, man. Sorry that I can't upvote yet...Thrower

© 2022 - 2024 — McMap. All rights reserved.