我正在尝试使用基于https://github.com/exupero/saveSvgAsPng和http://techslides.com/save-svg-as-an-image的方法将在浏览器中创建的SVG(一个d3.js图表)导出为PNG。SVG被转换为数据URI并在画布中呈现为图像,然后转换为PNG数据URI。使用锚点标记将此URI作为文件下载。我已经确认在当前版本的FF、Chrome和Safari中可以正常工作;然而,在Edge触发锚点标签上的下载会导致Edge要么卡住(只有控制台中的doctype警告),要么完全崩溃。是否有办法使其在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
}