Creating animations with JavaScript
Before discussing animations in JavaScript or D3, we need to make sure what defines an animation. An animation is a timed sequence of transformations on one or multiple elements to create an effect of motion.
Timers and intervals in D3
Animation are timed transitions; therefore, we need to keep track of the time in an animation. If we are dealing with a huge number of elements, we have to manually keep a track of a huge number of timers. Luckily, D3 provides an abstraction for timers and interval function with the d3.timer(tickFn[, delay[, time]])
method. This timer function calls tickFn
repeatedly after the relative delay
or at an absolute date time
until it returns true
.
Let's write the previous JavaScript animation example with D3 timers:
<svg width="800" height="600"> <rect x="50" y="60" width="100" height="100"></rect> </svg> <script> var rect = d3.select('rect:nth-of-type(1)'); animate(rect, 'x', 50, 650); function animate...