Animation with requestAnimationFrame
Build smooth canvas animations with the animation frame loop.
Why requestAnimationFrame?
requestAnimationFrame (rAF) schedules a callback before the next browser repaint, synchronizing animation to the display refresh rate (typically 60fps). Unlike setInterval, rAF pauses when the tab is hidden, saving CPU and battery.
Basic Animation Loop
A rAF loop: define an animate function that draws the current frame, then calls requestAnimationFrame(animate) to schedule the next. The browser calls animate before each repaint, creating a continuous animation at the display's frame rate.
function animate(timestamp) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// draw frame at current state
draw(timestamp);
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);All lessons in this course
- Setting Up the Canvas and 2D Context
- Drawing Rectangles and Paths
- Text and Images on Canvas
- Animation with requestAnimationFrame