Animating with requestAnimationFrame
In this section, you will use the useEffect
hook in combination with window.requestAnimationFrame
to adjust the positioning of AnimatedLine
and Turtle
.
The window.requestAnimationFrame
function is used to animate visual properties. For example, you can use it to increase the length of a line from 0 units to 200 units over a given time period, such as 2 seconds.
To make this work, you provide it with a callback that will be run at the next repaint interval. This callback is provided with the current animation time when it’s called:
const myCallback = time => { // animating code here }; window.requestAnimationFrame(myCallback);
If you know the start time of your animation, you can work out the elapsed animation time and use that to calculate the current value of your animated property.
The browser can invoke your callback at a very high refresh rate, such as 60 times per second. Because of these very small intervals...