0Pricing
JavaScript Academy · Lesson

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

  1. Setting Up the Canvas Context
  2. Drawing Shapes and Paths
  3. Working with Images and Text
  4. Animation with requestAnimationFrame
← Back to JavaScript Academy