-
-
Save rduque1/1c950351dfed65efe3d5d15ccccf58e5 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