Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
}
like image 741
xJREB Avatar asked May 07 '14 10:05

xJREB


People also ask

Does canvas support SVG?

We are redesigning some icons and graphics for our courses and our graphics person suggest SVG is going to display with the highest quality but does not appear to be supported in Canvas.

What is CTX drawImage?

The drawImage() method is a method from the Canvas API that allows you to add an image into your <canvas> element. Just like the fillRect() method, the drawImage() method is a part of Canvas 2D API, so you need to get the Context object of your <canvas> element first and call the method from there.


1 Answers

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.

like image 105
Robert Longson Avatar answered Oct 07 '22 19:10

Robert Longson