Transitions
D3 can animate any CSS property by creating a special selection object for handling transitions.
We'll cover the following
It is time to finally talk about animations. Animations can be performed with CSS. However, there are specific properties on SVG images that can not be animated. This limitation makes it hard to animate charts. Luckily, D3 provides a package called D3 transition. You can find it here:
https://github.com/d3/d3-transition
This package is capable of transitioning between colors, coordinates, sizes, and other attributes. By default, this package is bundled with the core of D3. We do not have to do anything to include it.
Advantages of the D3 transition package
There are a couple of advantages for allowing D3 to handle animations with the transition library. Firstly, as mentioned earlier, it’s able to animate any property.
Secondly, it can synchronize animations. We are going to be animating multiple shapes at once, and D3 can handle this easily.
Thirdly, we can play multiple animations one after another. We can chain animations instead of playing them all at once. Too much animation can make it hard to keep track of what is happening. We can make it easier to understand what is going on by breaking animations down into smaller groups. We will look at what this means in a later lesson.
Lastly, animations can be interrupted. If for whatever reason, we need to stop animation in progress, D3 allows us to do that.
There are studies out there that say JavaScript animations are less performant than CSS animations. This is somewhat true. However, D3 is very performant, as you will see in a moment.
Animating the chart
D3 makes it incredibly easy to animate shapes. It is only going to take one line of code. There are three things we’re going to animate, the bars, labels, and the axis. All three can be animated. Let’s start with the bars.
D3 comes with a function called transition()
that we can chain on selections. We are going to chain the transition()
function after the join()
function.
Get hands-on with 1400+ tech skills courses.