Animation with transitions

D3 transitions are one way of accomplishing animation with transitions. Transitions use the familiar principle of changing a selection's attributes, except that the changes are applied over time. Transitions, easings, and the like are provided in the d3-transition package.

To slowly turn all rectangles on the page into red, we will use the following line of code:

d3.selectAll('rect').transition().style('fill', 'red');

We start a new transition with .transition() and then define the final state of each animated attribute. By default, every transition takes 250 milliseconds; you can change the timing with .duration(). New transitions are executed on all properties simultaneously unless you set a delay using .delay().

Delays are handy when we want to make transitions happen in sequence. Without a delay, they are all executed at the same time, depending on an internal timer. The easiest way to create a sequence of transitions is to nest transition calls--each delay will be relative to the most recent transition:

d3.select('rect')
.style('fill', 'green')
.transition()
.delay(2000)
.style('fill', 'red')
.transition()
.delay(1000)
.style('fill', 'blue')

This will fill the selected rectangle; wait two seconds and transition it to being red, then wait another second and transition it to being blue.

Delays being relative to the last transition is a significant change from D3 v3! Previously, delays were relative to the first transition in the chain and were a bit of a pain to orchestrate.

If you want to do something before a transition begins, or want to listen for it to end, you can use .on() with the appropriate event type. Add the following to the preceding code:

.style('fill', 'red') 
.on('start', () => { console.log("I'm turning red!"); })
.on('end', () => { console.log("I'm all red now!"); })

This is a fairly major change in D3 v4; previously, you would use transition.each() to listen for transition events. In D3 v4, transition.each() works identically to selection.each(), that is, it takes a callback containing the datum, index, and context of the current element and allows you to invoke arbitrary code on each element.

This is handy for making instant changes before or after a transition. Just keep in mind that transitions run independently and you cannot rely on transitions outside the current callback being in this state or that.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset