D3.js donut chart
by jdcast
HTML
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://gabelerner.github.io/canvg/rgbcolor.js"></script>
<script src="http://gabelerner.github.io/canvg/StackBlur.js"></script>
<script src="http://gabelerner.github.io/canvg/canvg.js"></script>
CSS
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
margin: auto;
position: relative;
width: 960px;
}
text {
font: 10px sans-serif;
}
form {
position: absolute;
right: 10px;
top: 10px;
}
JavaScript
var dataset = {
apples: [53245, 28479, 19697, 24037, 40245],
};
var width = 460,
height = 300,
radius = Math.min(width, height) / 2;
var color = d3.scale.category20();
var pie = d3.layout.pie()
.sort(null);
var arc = d3.svg.arc()
.innerRadius(radius - 100)
.outerRadius(radius - 50);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var path = svg.selectAll("path")
.data(pie(dataset.apples))
.enter().append("path")
.attr("fill", function(d, i) { return color(i); })
.attr("d", arc);
var html = d3.select("svg")
.attr("title", "test2")
.attr("version", 1.1)
.attr("xmlns", "http://www.w3.org/2000/svg")
.node().parentNode.innerHTML;
d3.select("body").append("div")
.attr("id", "download")
.html("Right-click on this preview and choose Save as<br />Left-Click to dismiss<br />")
.append("img")
.attr("src", "data:image/svg+xml;base64,"+ btoa(html));
// Select the first svg element
var svg = d3.select("svg")[0][0],
img = new Image(),
serializer = new XMLSerializer(),
svgStr = serializer.serializeToString(svg);
img.src = 'data:image/svg+xml;base64,'+window.btoa(svgStr);
// You could also use the actual string without base64 encoding it:
//img.src = "data:image/svg+xml;utf8," + svgStr;
var canvas = document.createElement("canvas");
document.body.appendChild(canvas);
canvas.width = 100;
canvas.height = 100;
canvas.getContext("2d").drawImage(img,0,0,100,100);
window.open(img.src);