Skip to content

Instantly share code, notes, and snippets.

@sxywu
Last active August 29, 2015 14:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sxywu/33bc932b850792e832f8 to your computer and use it in GitHub Desktop.
Save sxywu/33bc932b850792e832f8 to your computer and use it in GitHub Desktop.
How D3 Transitions Work, Pt. 1: d3.interpolate
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.js" charset="utf-8"></script>
</head>
<body>
<div>
<button onclick="play()">play</button>
</div>
<svg></svg>
<script>
var startX = 100;
var endX = 500;
var svg = d3.select('svg')
.attr('width', 600)
.attr('height', 200);
var circle = svg.append('circle')
.attr('cx', startX)
.attr('cy', 100)
.attr('r', 25)
.attr('fill', '#3FB8AF');
var start = null;
var duration = 1000;
var interpolate = d3.interpolate(startX, endX);
// adapted from MDN example for requestAnimationFrame
// (https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
function step(timestamp) {
if (!start) start = timestamp;
var progress = timestamp - start;
// use d3 interpolate to calculate cx at time t
var t = progress / duration;
var cx = interpolate(t);
circle.attr('cx', cx);
if (progress < duration) {
window.requestAnimationFrame(step);
}
}
// callback for clicking on play button
function play() {
start = null;
circle.attr('cx', startX);
window.requestAnimationFrame(step);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment