我正在尝试使用基于 https://github.com/exupero/saveSvgAsPng 的方法将浏览器中创建的 SVG(d3.js 图表)导出为 PNG。和 http://techslides.com/save-svg-as-an-image . SVG 被转换为数据 URI 并呈现为 Canvas 中的图像, Canvas 被转换为 PNG 数据 URI。此 URI 使用 anchor 标记作为文件下载。我已经能够确认这适用于当前版本的 FF、Chrome 和 Safari;但是,触发 anchor 标记上的下载会导致 Edge 挂起(控制台中只有文档类型警告)或完全崩溃。有没有办法让它在 Edge 中运行,或者是否还没有完全支持数据 URI 的 anchor 下载?
从上述来源创建的代码:
//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 作为 anchor 标记的 href。它会接受它作为 img 标签的来源。我能想到的最佳解决方案是使用 download.js下载文件。但是,您将遇到的下一个问题是,当您将图像标签的 src 设置为 SVG 以进行 PNG 渲染时,“加载”事件不会在该图像对象的 Edge 中触发。还没有办法解决这个问题。
关于javascript - 如何在 Edge 中下载图像/png 数据 URI?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37280154/