Skip to content

Instantly share code, notes, and snippets.

@hudsonb
Forked from mbostock/.block
Last active January 29, 2018 17:45
Show Gist options
  • Save hudsonb/d97c230080074bd4e449f1deb63cc381 to your computer and use it in GitHub Desktop.
Save hudsonb/d97c230080074bd4e449f1deb63cc381 to your computer and use it in GitHub Desktop.
Stroke Dash Interpolation
license: gpl-3.0

By interpolating the stroke-dasharray style property, you can animate a stroke from start to end. This might be used to convey directionality of connected links in a network graphic, such as our graphic of Academy Award nominees. By setting the transition duration proportional to the length of the line and using linear easing, you can further animate the stroke at constant speed.

A related technique is point-along-path interpolation.

<!DOCTYPE html>
<meta charset="utf-8">
<body>
<style>
path {
fill: none;
stroke: #000;
stroke-width: 3px;
}
</style>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var points = [
[480, 200],
[580, 400],
[680, 100],
[780, 300],
[180, 300],
[280, 100],
[380, 400]
];
var line = d3.svg.line()
.tension(0) // Catmull–Rom
.interpolate("cardinal-closed");
var svg = d3.select("body").append("svg")
.datum(points)
.attr("width", 960)
.attr("height", 500);
var dashing = "4, 4"
var path = svg.append("path")
.style("stroke-dasharray", dashing)
.attr("d", line)
.call(transition);
var length = path.node().getTotalLength()
var dashLength =
dashing
.split(/[\s,]/)
.map(function (a) { return parseFloat(a) || 0 })
.reduce(function (a, b) { return a + b });
function transition(path) {
path.transition()
.duration(7500)
.tween("pathTween", function() { return tweenPath })
.each("end", function() { d3.select(this).call(transition); });
}
function tweenPath(t) {
var l = length * t;
path.attr("stroke-dashoffset", l);
var n = Math.ceil(l / dashLength);
var newDashes = new Array(n).join( dashing + " " );
var dashArray = "0, " + l + " " + newDashes + " 0, " + length;
path.attr("stroke-dasharray", dashArray);
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment