Course contentsShow
← Web Development
Lesson 2626 of 2,98247. Data VisualizationFree lesson

Canvas Animation Basics

Creating smooth animations using requestAnimationFrame and clearing/redrawing the canvas efficiently.

Canvas Animation Basics

You'll learn how to create smooth, performant animations on the canvas by continuously clearing and redrawing frames.

The Core Idea

Think of canvas animation like a flipbook: each frame is a fresh drawing that creates the illusion of movement when shown rapidly. Unlike SVG where you update properties and the browser handles redrawing, canvas requires you to manually clear and repaint the entire scene (or parts of it) for each frame.

The key is requestAnimationFrame, which tells the browser "call this function right before the next repaint" — typically 60 times per second. This synchronizes your animation with the browser's refresh cycle for buttery-smooth motion.

The Animation Loop Pattern

Here's the fundamental structure:

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

let x = 0;

function animate() {
  // 1. Clear the canvas
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  
  // 2. Update your data/positions
  x += 2;
  if (x > canvas.width) x = 0;
  
  // 3. Draw the new frame
  ctx.fillStyle = 'blue';
  ctx.fillRect(x, 50, 40, 40);
  
  // 4. Schedule the next frame
  requestAnimationFrame(animate);
}

// Start the loop
animate();

Efficient Clearing Strategies

For simple animations, clearRect over the entire canvas works well. For complex scenes, consider clearing only the "dirty" regions that changed, or use double buffering techniques with off-screen canvases.

Why requestAnimationFrame?

It automatically pauses when the tab is inactive (saving CPU), synchronizes with display refresh rates, and batches repaints efficiently — much better than setInterval or setTimeout.

Key Takeaway: Canvas animation requires a clear-update-draw-repeat cycle using requestAnimationFrame for smooth, performant motion that respects the browser's rendering pipeline.