What is transition ?
When the state of an element changes from current state to desired state, transition helps to apply the change smoothly by interpolating the states between the two end states. D3 transitions are interpolation-based animation. D3 uses various built-in interpolators to calculate the intermediary state and applying the states smoothly to the DOM element giving a feel of animation.
D3 transitions are provided by d3-transition module. So lets install it.
So how do we apply transition to an element ? Its simple and just a single line of code:
In Line2 we have used the transition() method which returns a new selection with all the elements that were already present in the selection returned by select() but the new selection has each of its element bound to transition. On a transition-bound selection we can call normal selection methods like attr(), style() etc. (but not all). After the transition() method is introduced , any change in style, attr etc will be transitioned smoothly by D3.
Starting the transition after a delay
In the above example the transition/animation starts as soon as the page loads. if we want our animation to start after a certain time, we can use the delay() method of the transition selection.
Specifying the duration of the transition
By default D3 applies the transition for a duration of 250 ms. If we want to specify our own duration use the duration() method as shown below:
Run this code in your browser:
You will notice that the transition starts slow, gains acceleration in the middle and slows down towards the end. This quality of motion used for transition is known as easing. If we don’t specify an ease, D3 by default uses “cubic-in-out” which is what we saw in the above example. D3 provides ease() method to specify the easing function. There are a whole bunch of built-in easing functions in D3 like d3.easeLinear, d3.easeElastic etc. You can check the API Reference.
Lets look at some of the easing function in action:
(Click on Run with JS button to replay the animation)
Using Transition Chaining
Till now we have seen single transition in our examples. In D3, transitions can be chained so that when one transition finishes next transition in the chain takes off. Lets see an example:
Click on the HTML tab to see the code. Below is the relevant portion:
Listening to transitional events
D3 provides the on() method to register listener for transitional events:
- transition.on(eventType, [listener])
Here the eventType can be any of the following string:
- start : triggered when the transition starts
- end : triggered when the transition ends
- interrupt : triggered when the transition is interrupted
If you check in browser console, we will see “Started” when the transition starts and “Finished” once the transition ends.