I am trying to export an SVG created in the browser (a d3.js chart) as a PNG using methods based from https://github.com/exupero/saveSvgAsPng and http://techslides.com/save-svg-as-an-image. The SVG is converted to a data URI and rendered as an image in a canvas, which is converted to a PNG data URI. This URI is downloaded as a file using an anchor tag. I have been able to confirm this to work in current versions of FF, Chrome, and Safari; however, triggering the download on the anchor tag causes Edge to either hang (with only a doctype warning in the console) or crash completely. Is there anyway to get this to work in Edge or is the anchor download with data URI not fully supported yet?
Code created from the sources above:
//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
}