Demonstrates how to use the getTotalLength and getPointAtLength methods on SVG path elements to interpolate a point along an existing path, and how to animate the stroke using the stroke-dasharray style. Built with D3. Forked (and tweaked) from Mike Bostock's original.
-
-
Save johan/1315145 to your computer and use it in GitHub Desktop.
Point-Along-Path Interpolation
This file contains hidden or 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> | |
<html> | |
<head> | |
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/> | |
<title>Point-Along-Path Interpolation</title> | |
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js?2.4.6"></script> | |
<style type="text/css"> | |
path { | |
cursor: pointer; | |
fill: #eee; | |
stroke: #666; | |
stroke-width: 1.5px; | |
} | |
circle { | |
fill: steelblue; | |
stroke: white; | |
stroke-width: 1.5px; | |
} | |
</style> | |
</head> | |
<body> | |
<script type="text/javascript"> | |
var w = 960, | |
h = 500; | |
var svg = d3.select("body").append("svg:svg") | |
.attr("width", w) | |
.attr("height", h) | |
.append("svg:g") | |
.attr("transform", "translate(" + w / 2 + "," + h / 2 + ")"); | |
var path = svg.append("svg:path") | |
.attr("d", d3.svg.arc() | |
.innerRadius(h / 4) | |
.outerRadius(h / 3) | |
.startAngle(0) | |
.endAngle(Math.PI)); | |
var circle = svg.append("svg:circle") | |
.attr("r", 6.5) | |
.attr("transform", "translate(0," + -h / 3 + ")"); | |
var draw = 0; | |
function transition() { | |
circle.transition() | |
.duration(5000) | |
.attrTween("transform", translateAlong(path.node())); | |
path.transition() | |
.duration(5000) | |
.styleTween("stroke-dasharray", strokeAlong(path.node())) | |
.each("end", transition); | |
draw = 1 - draw; | |
} | |
transition(); | |
// Returns an attrTween for translating along the specified path element. | |
function translateAlong(path) { | |
var l = path.getTotalLength(); | |
return function(d, i, a) { | |
return function(t) { | |
var p = path.getPointAtLength(t * l); | |
return "translate(" + p.x + "," + p.y + ")"; | |
}; | |
}; | |
} | |
// Returns an attrTween for stroking along the specified path element. | |
function strokeAlong(path) { | |
var l = path.getTotalLength(); | |
return function(d, i, a) { | |
return function(t) { | |
var stroked = t * l, not = l - stroked; | |
return (draw ? '' : '0,') + stroked + "," + not; | |
}; | |
}; | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment