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

The Animation Loop

4 slides · use ←/→ or Space to navigate, F for fullscreen.

Reading view

← Back to the full Chapter 7 deck

The Animation Loop
Fullscreen for presentation · Print / PDF for a handout
1 / 4
Lesson

The Animation Loop

Continuous rendering with requestAnimationFrame().

The Animation Loop

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.
The Animation Loop

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.
The Animation Loop

Activity — complete the code

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