Skip to content

Instantly share code, notes, and snippets.

@mattsacks
Created June 6, 2012 23:15
Show Gist options
  • Save mattsacks/2885435 to your computer and use it in GitHub Desktop.
Save mattsacks/2885435 to your computer and use it in GitHub Desktop.
Multi-Point Line Animation

Animating the addition/subtraction of points along a path causes jerkiness. This is a demonstration of what that could look like between 5-15 points on a normal distribution.

It can probably be solved in some way by re-drawing the line with the new number of points, interpolating between the old number of points so that it looks exactly the same - then just animating those points to their new coordinate.

<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>D3 Multiple-Point Line Transition</title>
<style type='text/css'>
/*<![CDATA[*/
path {
stroke: black;
fill: none;
}
/*]]>*/
</style>
</head>
<body>
<script src='http://d3js.org/d3.v2.js?2.9.1'></script>
<script type='text/javascript'>
//<![CDATA[
var path = undefined;
var updateFunctions = function() {
n = Math.floor(Math.random() * (15 - 5 + 1)) + 5;
data = d3.range(n).map(d3.random.normal(0, 0.2));
x = d3.scale.linear()
.domain([0, n-1])
.range([0, 960]);
y = d3.scale.linear()
.domain([d3.min(data), d3.max(data)])
.range([500, 0]);
line = d3.svg.line()
.interpolate('basis')
.x(function(d,i) { return x(i); })
.y(y);
}
var createPath = function() {
return svg.selectAll('path')
.data([data])
.enter()
.append('svg:path');
}
var svg = d3.select('body').append('svg')
.attr('width', 960)
.attr('height', 500);
onInterval = function() {
updateFunctions();
if (!window.path) {
window.path = createPath().attr('d', line);
} else {
window.path
.data([window.data])
.transition()
.duration(200)
// this is the same as .attr('d', line)
.attrTween('d', function(d,i,a) {
return d3.interpolate(a, window.line(d));
});
}
};
setInterval(onInterval, 750);
//]]>
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment