Created
October 31, 2013 16:27
-
-
Save pr3ssh/7252659 to your computer and use it in GitHub Desktop.
D3js Animate an Arc
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
<!DOCTYPE html> | |
<!-- Based on the code: http://mikeheavers.com/main/code-item/svg_path_animations_with_d3 --> | |
<html> | |
<head> | |
<title>Arc Tween</title> | |
<script src="http://d3js.org/d3.v3.min.js"></script> | |
</head> | |
<body> | |
<div id="chart"></div> | |
<script> | |
var w = 960, //canvas width | |
h = 900, //canvas height | |
r = Math.min(w, h) / 3; //radius of the circle my arc will follow | |
s = .09; //arc spacing | |
var arc = d3.svg.arc() | |
.startAngle(0) | |
.endAngle(function(d) { return d.value * 2 * Math.PI; }) | |
.innerRadius(function(d) { return r; }) | |
.outerRadius(function(d) { return (d.index + s) * r; }); | |
var vis = d3.select("#chart").append("svg") | |
.attr("width", w) | |
.attr("height", h) | |
.append("g") | |
.attr("transform", "translate(" + w / 2 + "," + h / 2 + ")"); | |
var g; | |
g = vis.selectAll("g") | |
.data(buildPercBars) | |
.enter().append("g") | |
.attr("class", "arc"); | |
g.append("path") | |
.style("fill", "93cfeb") | |
.attr("d", arc); | |
g.append("text") | |
.text("Press any key to start"); | |
// Generate the percentage bars | |
function buildPercBars() { | |
return [ | |
{value: .45, index: .5}, | |
]; | |
} | |
window.addEventListener("keypress", selectArcs, false); | |
function selectArcs() { | |
d3.selectAll("g.arc > path") | |
.each(arcTween); | |
} | |
function arcTween(){ | |
d3.select(this) | |
.transition().duration(1000) | |
.attrTween("d", tweenArc({ value : 0 })); | |
d3.select("text") | |
.style("visibility", "hidden"); | |
} | |
function tweenArc(b) { | |
return function(a) { | |
var i = d3.interpolate(a, b); | |
for (var key in b) a[key] = b[key]; // update data | |
return function(t) { | |
return arc(i(t)); | |
}; | |
}; | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment