1

I'm trying to convert a SVG file to PNG by drawing it to canvas.

var svgToCanvas = function(svgElement) {
  setNameSpaceOnEl(svgElement);
  appendCSSRules(svgElement, getCssRules(svgElement));

  var image = new Image();

  // this is ugly but will do:
  var svgXml = $('<div>').append($(svgElement).clone()).html();
  var b64str = btoa(unescape(encodeURIComponent(svgXml)));
  // var svgXml = new XMLSerializer().serializeToString(svgElement);

  var defer = $q.defer();

  image.onload = function() {
    var canvas = document.createElement('canvas');
    canvas.width = image.width;
    canvas.height = image.height;
    var context = canvas.getContext('2d');
    context.drawImage(image, 0, 0);
    defer.resolve(canvas);
  };
  image.src = 'data:image/svg+xml;base64,' + b64str;
  return defer.promise;
};

The problem is that even though the image handling takes place inside the onload function, Firefox yields error NS_ERROR_NOT_AVAILABLE: ... on the line

context.drawImage(image, 0, 0);.

With breakpoints I see the image.src at this point is a valid base64 string, and I can even open up the image itself.

The code above works in Chrome, but not in Firefox. Any suggestions how to get around this in Firefox?

amergin
  • 962
  • 1
  • 12
  • 32
  • Does the outer `` element have width and height attributes? – Robert Longson Jul 04 '14 at 04:56
  • Yes, the the element does have those attributes: `..`. Looking at this more closely, it seems to be because Firefox [does not support this](http://stackoverflow.com/questions/3768565/drawing-a-svg-file-on-a-html5-canvas/3769883#3769883) yet. – amergin Jul 04 '14 at 19:33
  • That answer is 4 years old. Firefox has supported this for just slightly less than 4 years. – Robert Longson Jul 04 '14 at 21:30
  • The edit says April 2014. – amergin Jul 05 '14 at 13:43
  • For example, my Firefox 30.0 fails on [this jsfiddle](http://jsfiddle.net/Na6X5/) with the same error. – amergin Jul 05 '14 at 13:57
  • The image and the page are on different domains. That's why the jsfiddle fails. Is that what you're trying to do, if so it won't work as the browser's security model won't permit it. – Robert Longson Jul 05 '14 at 14:14
  • Nope, in my case the svg is dynamically created to DOM and everything takes place on the same domain (at this point localhost webserver). – amergin Jul 05 '14 at 14:31

0 Answers0