简体   繁体   English

在画布上从SVG导出PNG

[英]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. 我的目标是获取HTML,并将其导出为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. 我读到最好的方法是将HTML包装在SVG和foreignObject元素中,然后将其绘制在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. 问题是,当我这样做时,我发现由于tainted canvas cannot be exported错误消息tainted canvas cannot be exported 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. 我已经验证了其中大部分功能,除了canvas.toDataURL()调用之外。 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. 是的,SVG在现代浏览器中弄脏了画布。

You can no longer use the foreignObject hack to scrape an html element. 您不再可以使用foreignObject hack抓取html元素。

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. Chrome有一个名为ScreenShot的插件,可让您抓取内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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