Skip to content

Instantly share code, notes, and snippets.

@iwek
Created October 23, 2013 16:26
Show Gist options
  • Save iwek/7121872 to your computer and use it in GitHub Desktop.
Save iwek/7121872 to your computer and use it in GitHub Desktop.
D3js click function to save SVG as dataurl in IMG tag, load into CANVAS and save as PNG dataurl, and auto download the actual PNG file.
d3.select("#save").on("click", function(){
var html = d3.select("svg")
.attr("version", 1.1)
.attr("xmlns", "http://www.w3.org/2000/svg")
.node().parentNode.innerHTML;
//console.log(html);
var imgsrc = 'data:image/svg+xml;base64,'+ btoa(html);
var img = '<img src="'+imgsrc+'">';
d3.select("#svgdataurl").html(img);
var canvas = document.querySelector("canvas"),
context = canvas.getContext("2d");
var image = new Image;
image.src = imgsrc;
image.onload = function() {
context.drawImage(image, 0, 0);
var canvasdata = canvas.toDataURL("image/png");
var pngimg = '<img src="'+canvasdata+'">';
d3.select("#pngdataurl").html(pngimg);
var a = document.createElement("a");
a.download = "sample.png";
a.href = canvasdata;
a.click();
};
});
@iwek
Copy link
Author

iwek commented Oct 23, 2013

For SVG to Image Conversion: http://techslides.com/save-svg-as-an-image/

@ppierce01
Copy link

Hello I hope you are still answering questions on this subject. I am learning D3 and have attempted to use your solution to save my SVG as an image. However when click the save button I get an error message. on this line of code:
var imgsrc = 'data:image/svg+xml;base64,'+ btoa(html);
I am using it in an aspx page with visual studios 2013
debugging - Microsoft visual studio administrator

Any suggestions on solving this issue would be appreciated.

Thanks
Perry

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment