Animation Fundamentals: RequestAnimationFrame
Learn about the requestAnimationFrame API and how to use it to create smooth and efficient animations on the canvas.
Animation Fundamentals: requestAnimationFrame
This section explores the fundamentals of animation on the HTML canvas, focusing on the requestAnimationFrame
API. Using requestAnimationFrame
is essential for creating smooth and efficient animations.
Understanding requestAnimationFrame
requestAnimationFrame
is a browser API that tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint. This is the key to performant canvas animations.
Instead of using setInterval
or setTimeout
, which can lead to dropped frames and jerky animation, requestAnimationFrame
synchronizes the animation with the browser's refresh rate. This typically results in 60 frames per second (FPS) on most displays, leading to smoother visuals.
How requestAnimationFrame
Works
- You call
requestAnimationFrame(callback)
, wherecallback
is the function you want to execute for each animation frame. - The browser adds
callback
to a queue. - Before the next repaint, the browser executes all functions in the queue.
- Inside the
callback
function, you update the canvas and then callrequestAnimationFrame
again to schedule the next frame. This creates the animation loop.
Basic Usage Example
Here's a simple example of how to use requestAnimationFrame
to animate a circle moving across the canvas:
// Get the canvas element
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// Initial position and speed of the circle
let x = 0;
let speed = 2;
function animate() {
// Clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw the circle
ctx.beginPath();
ctx.arc(x, canvas.height / 2, 20, 0, Math.PI * 2);
ctx.fillStyle = 'blue';
ctx.fill();
// Update the position
x += speed;
// Bounce off the edges
if (x + 20 > canvas.width || x - 20 < 0) {
speed = -speed;
}
// Call requestAnimationFrame to schedule the next frame
requestAnimationFrame(animate);
}
// Start the animation loop
animate();
Benefits of Using requestAnimationFrame
- Smooth Animations: Synchronizes with the browser's refresh rate, resulting in smoother visuals.
- Performance: The browser optimizes when to run the animation, avoiding unnecessary updates when the tab is inactive or the animation is off-screen.
- Battery Life: By only rendering when necessary, it reduces CPU usage and extends battery life on mobile devices.
Browser Compatibility
requestAnimationFrame
is widely supported in modern browsers. For older browsers, you can use a polyfill.
Conclusion
requestAnimationFrame
is the recommended way to create animations on the HTML canvas. By understanding how it works and leveraging its benefits, you can create smooth, efficient, and performant animations for your web applications.