简体   繁体   中英

Tainted Canvas with canvas.toBlob

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM