Click play to animate.
My quest to understand how transitions work under the hood, part 2: animating using d3.interpolate and window.requestAnimationFrame.
Part 2 here: How D3 Transitions Work, Pt. 2: d3.interpolate with multiple elements
Click play to animate.
My quest to understand how transitions work under the hood, part 2: animating using d3.interpolate and window.requestAnimationFrame.
Part 2 here: How D3 Transitions Work, Pt. 2: d3.interpolate with multiple elements
<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> |