4

I am trying to convert a svg to an image and prompt a download to the user.

var chart = $(svg.node())
            .attr('xmlns', 'http://www.w3.org/2000/svg');
var width = that.svg_width;
var height = that.svg_height;
var data = new XMLSerializer().serializeToString(chart.get(0));
var svg1 = new Blob([data], { type: "image/svg+xml;charset=utf-8" });
var url = URL.createObjectURL(svg1);

var img = $('<img />')
            .width(width)
            .height(height);
img.attr('crossOrigin' ,'' );
img.bind('load', function() {
        var canvas = document.createElement('canvas');
        canvas.width = width;
        canvas.height = height;
        var ctx = canvas.getContext('2d');
        ctx.drawImage(img.get(0), 0, 0);
        canvas.toBlob(function(blob) { // this is where it fails
                saveAs(blob, "test.png");
        });
});
img.attr('src', url);

Chrome throws an exception saying "Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported." at canvas.toBlob

There is no cross origin involved in this case. The svg is on the same page which i am converting to an image and trying to load in canvas. So how is the canvas tainted? Am I missing something?

Srinivas
  • 727
  • 4
  • 14

1 Answers1

5

After some digging came across https://code.google.com/p/chromium/issues/detail?id=294129. My svg was having a < foreignObject > (d3 based chart) and that's why i was having this issue.

Using the data uri instead of loading the svg from the blob solved my issue

Srinivas
  • 727
  • 4
  • 14
  • 1
    But for when you change from blob to data url it will work in Chrome and not in Firefox – DaNeSh Nov 12 '15 at 17:05
  • How did you use a data URI instead of loading SVG from blob? Do you have a code snippet by any chance? – LondonAppDev Aug 25 '16 at 15:23
  • 1
    instead of `new Blob([data], { type: "image/svg+xml;charset=utf-8" });` write `"data:image/svg+xml;charset=utf-8," + data;`. It gives you a url, which goes to `img.src` in bypass evil `createObjectURL` – primetwig Feb 27 '17 at 14:25