SVG Download
by kenta_torii
HTML
<script src="http://d3js.org/d3.v3.js"></script>
<div id="viz"></div>
<a href="#" id="download">Download</a>
CSS
#download{
cursor: pointer;
text-decoration: none;
color: black;
}
JavaScript
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");
});
};