Created
October 23, 2013 16:26
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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
Any suggestions on solving this issue would be appreciated.
Thanks
Perry