The Animation Loop
Continuous rendering with requestAnimationFrame().
The Animation / Game Loop — Concept
How continuous rendering works in a browser:
- Start — call
animate()orgameLoop(). - Update — move objects, change state.
- Clear —
ctx.clearRect()to wipe the canvas. - Draw — render all objects.
- 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
| Step | Action |
|---|---|
| 1. Update state | Call update() to advance position, size or other properties. |
| 2. Clear canvas | Erase the previous frame so old drawings do not persist. |
| 3. Redraw | Call draw() to paint the object in its new position. |
| 4. Schedule next | Pass 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 stateanimatedObject.();// 2. Wipe the canvasctx.(0, 0, canvas.width, canvas.height);// 3. Redraw the objectanimatedObject.(ctx);// 4. Schedule the next frame(animate);}animate(); // kick off the loop