简体   繁体   中英

Export PNG from SVG on a Canvas

This is sort of a complicated question:

My goal is to take HTML, and export it as a PNG. I read that the best way to do this was to wrap HTML within an SVG and foreignObject element, and draw it on an HTML5 Canvas. The problem is, when I do that, I'm finding it impossible to export due to a tainted canvas cannot be exported error message. Here is my code:

var data = "<svg width=200 height=200>" +
            "<foreignObject width=100% height=100%>" +
            document.getElementById("textbox").innerHTML +
            "</foreignObject>" +
            "</svg>";

var serialized = new XMLSerializer().serializeToString(data.toDOM());

var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var DOMURL = window.URL || window.webkitURL || window;

var img = new Image();
var svg = new Blob([serialized], {type: 'image/svg+xml;charset=utf-8'});
var url = DOMURL.createObjectURL(svg);

img.onload = function () {
    ctx.drawImage(img, 0, 0);
    DOMURL.revokeObjectURL(url);
    window.open(canvas.toDataURL("image/png")); //this is the line with the error
}

img.src = url;

I have verified most of this is working, with the exception of that canvas.toDataURL() call. Am I missing something here? Is there a way to get this to work I'm overlooking? Thanks...

Yes, SVG taints a canvas in modern browsers.

You can no longer use the foreignObject hack to scrape an html element.

Modern browsers have plugged that hole for very good security reasons.

There are no cross-browser alternatives -- again for very good security reasons.

Chrome has a plugin called ScreenShot which lets you scrape content.

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