Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14
Chapter 7

The Animation Loop

Continuous rendering with requestAnimationFrame().


The Animation / Game Loop — Concept

How continuous rendering works in a browser:

  1. Start — call animate() or gameLoop().
  2. Update — move objects, change state.
  3. Clear — ctx.clearRect() to wipe the canvas.
  4. Draw — render all objects.
  5. requestAnimationFrame(loop) — the loop repeats at frames per second.

Creating an Animation Loop

requestAnimationFrame() schedules a function to run before the next screen repaint — typically 60 times per second, making it ideal for smooth animations.

// Create an animated object instance
const animatedObject = new AnimatedObject(100, 100, 10, 'teal');

// Define our animation loop
function animate() {
  // 1. Update state
  animatedObject.update();

  // 2. Wipe the canvas
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // 3. Redraw the object
  animatedObject.draw(ctx);

  // 4. Schedule the next frame
  requestAnimationFrame(animate);
}

animate();   // kick off the loop
StepAction
1. Update stateCall update() to advance position, size or other properties.
2. Clear canvasErase the previous frame so old drawings do not persist.
3. RedrawCall draw() to paint the object in its new position.
4. Schedule nextPass the function to rAF; the browser calls it before the next paint.

Activity — complete the code

Complete the code correctly to mark this lesson as complete automatically.

Complete the animation loop.

const animatedObject = new AnimatedObject(100, 100, 10, "teal");
 
function animate() {
// 1. Update state
animatedObject.();
 
// 2. Wipe the canvas
ctx.(0, 0, canvas.width, canvas.height);
 
// 3. Redraw the object
animatedObject.(ctx);
 
// 4. Schedule the next frame
(animate);
}
 
animate(); // kick off the loop