wee*_*ser 5 html javascript svg microsoft-edge
我正在尝试使用基于https://github.com/exupero/saveSvgAsPng和http://techslides.com/save-svg-as的方法将在浏览器(d3.js图表)中创建的SVG导出为PNG。-一个图像。SVG将转换为数据URI,并在画布中呈现为图像,然后将其转换为PNG数据URI。使用定位标记将此URI下载为文件。我已经确认可以在FF,Chrome和Safari的当前版本中使用;但是,触发锚标记上的下载会导致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
}Run Code Online (Sandbox Code Playgroud)
意识到这是一个老问题,但对于其他人来说最终会在这里:Edge 和 IE 不支持 dataURL 作为锚标记的 href。但它会接受它作为 img 标签的来源。我能想到的最好的解决方案是使用download.js来下载文件。然而,您将遇到的下一个问题是,当您将图像标签的 src 设置为 SVG 来渲染 PNG 时,该 Image 对象的“load”事件不会在 Edge 中触发。目前还没有办法解决这个问题。