Tweening is a tool that allows you to tell D3.js how to calculate attributes during transitions without keyframes tracking. The problem with keyframes tracking is that it can develop performance issues if there is a lot of animation.
We are going to look at three examples of the use of tweening in this post. The examples are as follows.
- Counting numbers animation
- Changing font size animation
- Spinning shape animation
Counting Numbers Animation
This simple animation involves using the .tween() method to count from 0 to 25. The other information in the code determines the position of the element, the font-size, and the length of the animation.
In order to use the .tween() method you must make a function. You first give the function a name followed by providing the arguments to be used. Inside the function we indicate what it should do using the .interpolateRound() method which indicates to d3.js to count from 0 to 25. Below is the code followed by the animation.
You can see that the speed of the numbers is not constant. This is because we did not control for this.
Changing Font-Size Animation
The next example is more of the same. This time we simply make the size of a text change. TO do this you use the .text() method in your svg element. In addition, you now use the .styleTween() method. Inside this method we use the .interpolate method and set arguments for the font and font-size at the beginning and the end of the animation. Below is the code and the animation
Spinning Shape Animation
The last example is somewhat more complicated. It involves create a shape that spins in place. To achieve this we do the following.
- Set the width and height of the element
- Set the svg element to the width and height
- Append a group element to the svg element.
- Transform and translate the g element in order to move it
- Append a path to the g element
- Set the shape to a diamond using the .symbol(), .type(), and .size() methods.
- Set the color of the shape using .style()
- Set the .each() method to follow the cycle function
- Create the cycle function
- Set the .transition(), and .duration() methods
- Use the .attrTween() and use the .interpolateString() method to set the rotation of the spinning.
- Finish with the .each() method
Below is the code followed by the animation.
This animation never stops because we are using a cycle.
Conclusion
Animations can be a lot of fun when using d3.js. The examples here may not be the most practical, but they provide you with an opportunity to look at the code and decide how you will want to use d3.js in the future.