我正在尝试使用基于以下方法的方法将浏览器中创建的 SVG(d3.js 图表)导出为 PNGhttps://github.com/exupero/saveSvgAsPng https://github.com/exupero/saveSvgAsPng and http://techslides.com/save-svg-as-an-image http://techslides.com/save-svg-as-an-image。 SVG 被转换为数据 URI 并在画布中呈现为图像,画布又被转换为 PNG 数据 URI。使用锚标记将此 URI 作为文件下载。我已经能够确认这可以在当前版本的 FF、Chrome 和 Safari 中运行;但是,触发锚标记上的下载会导致 Edge 挂起(控制台中仅显示文档类型警告)或完全崩溃。是否有办法让它在 Edge 中工作,或者是否尚未完全支持带有数据 URI 的锚点下载?
从上述来源创建的代码:
//this gets the svg and inlines all styles. It has a property "source" as well as width and height of the SVG.
var svgDownload = getElementChildrenAndStyles(svgID);
var image = new Image();
image.onload = function () {
var canvas = document.createElement('canvas');
canvas.width = svgDownload.width;
canvas.height = svgDownload.height;
var ctx = canvas.getContext('2d');
ctx.fillStyle = "#FFFFFF";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(image, 0, 0);
var a = document.createElement("a");
a.download = "chart.png";
try {
console.log("converting canvas");
a.href = canvas.toDataURL("image/png");
console.log("canvas converted. triggering download");
document.body.appendChild(a);
a.addEventListener("click", function(e) {
a.parentNode.removeChild(a);
});
a.click();
}
catch (e){
//error handling
}
};
try {
console.log("making image source url");
//both methods of creating the image source here work in most browsers except Edge
//image.src = "data:image/svg+xml;base64," + btoa( svgDownload.source.join() );
image.src = window.URL.createObjectURL(new Blob(svgDownload.source, {"type": 'image/svg+xml;base64'}));
console.log("image source set");
}
catch (e){
//error handling
}
意识到这是一个老问题,但对于其他人来说最终会在这里:Edge 和 IE 不支持 dataURL 作为锚标记的 href。但它会接受它作为 img 标签的来源。我能想到的最好的解决方案是使用下载.js http://danml.com/download.html下载文件。然而,您将遇到的下一个问题是,当您将图像标签的 src 设置为 SVG 来渲染 PNG 时,该 Image 对象的“load”事件不会在 Edge 中触发。目前还没有办法解决这个问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)