Animation with requestAnimationFrame
Create smooth canvas animations.
Why requestAnimationFrame?
requestAnimationFrame(callback) schedules your draw function to run before the next screen repaint — typically 60 times per second. It pauses in background tabs, saving CPU and battery, unlike setInterval.
function frame() {
// draw one frame
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);The Basic Loop
An animation loop clears the canvas, updates state, draws, then re-schedules itself.
let x = 0;
function loop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(x, 50, 30, 30);
x += 2;
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);All lessons in this course
- Setting Up the Canvas Context
- Drawing Shapes and Paths
- Working with Images and Text
- Animation with requestAnimationFrame