Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Download svg generated from D3
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script>
<title>Download SVG</title>
<style type="text/css">
#download{
cursor: pointer;
text-decoration: none;
color: black;
}
</style>
</head>
<body>
<div id="viz"></div>
<a href="#" id="download">Download</a>
<script type="text/javascript">
// Modified from https://groups.google.com/d/msg/d3-js/aQSWnEDFxIc/k0m0-q-3h1wJ
d3.select("#viz")
.append("svg:svg")
.attr("width", 300)
.attr("height", 200)
.style("background-color", "WhiteSmoke")
.append("svg:rect")
.attr("fill", "aliceblue")
.attr("stroke", "cadetblue")
.attr("width", 60)
.attr("height", 40)
.attr("x", 50)
.attr("y", 50);
d3.select("#download")
.on("mouseover", writeDownloadLink);
function writeDownloadLink(){
var html = d3.select("svg")
.attr("title", "svg_title")
.attr("version", 1.1)
.attr("xmlns", "http://www.w3.org/2000/svg")
.node().parentNode.innerHTML;
d3.select(this)
.attr("href-lang", "image/svg+xml")
.attr("href", "data:image/svg+xml;base64,\n" + btoa(html))
.on("mousedown", function(){
if(event.button != 2){
d3.select(this)
.attr("href", null)
.html("Use right click");
}
})
.on("mouseout", function(){
d3.select(this)
.html("Download");
});
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment