Skip to content
Tutorials Center
My learning

Topics

Lesson 91 of 96 ยท Projects

Project: Canvas Animation

Build a canvas particle animation in TypeScript - typed vectors and particles, a physics step, a frame loop with an injectable scheduler and fixed time step, and a canvas-shaped renderer.

Animation is where the browser, math and state all meet. A canvas animation is a loop: update the world a little, draw it, repeat about 60 times per second with requestAnimationFrame. The trick to keeping such a program clean is separating three jobs: simulation (pure math that moves things), rendering (turning state into drawing calls) and the loop (deciding when to step).

In this project you build a fountain of particles: each particle has a position, velocity, color and lifetime, gravity pulls them down, they bounce off the floor and fade out. The three stages are the typed simulation, the frame loop with a fixed time step and an injectable scheduler (so the loop runs in the editor without a browser), and the renderer that draws to a canvas-shaped interface.

Stage 1: typed vectors, particles and a physics step

We start with small immutable types. A Vec is a 2D vector, and functions on it return new vectors, which keeps the math easy to reason about. Particles are plain data objects. The simulation function takes the current particles and a time step in seconds and returns the next particles.

TypeScript Stage 1: vectors, particles and a pure physics step

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Notice how much TypeScript is not in the way: everything is readonly, functions are small and the state is passed in and returned. stepWorld uses filter to remove expired particles, so the array is the only place lifetimes are tracked. The simulation never mentions a canvas, which means you could test it with plain numbers (does a dropped particle ever go below the floor?).

One physics detail: velocity is in pixels per second and dt is in seconds. Multiplying by dt makes the motion the same whether the program runs at 30, 60 or 144 frames per second, the key habit in animation code.

Stage 2: the frame loop and a fixed time step

In a browser, requestAnimationFrame(callback) calls you before the next repaint and passes a timestamp in milliseconds. Frame times vary: a busy tab may give 16 ms, then 50 ms. If you feed a variable dt straight into the physics, results become unstable (a very long frame can make particles tunnel through the floor).

The standard fix is a fixed time step with an accumulator: collect real elapsed time, and advance the simulation in equal slices of 1/60 second until you have caught up. We also inject the scheduler as an interface, so tests (and this editor) can drive frames by hand.

TypeScript Stage 2: a fixed-step loop with an injectable scheduler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Read the output line by line. The 50 ms gap produced three updates at once, because the accumulator caught up. Pausing cancels the pending frame, so the page stops consuming CPU, and resuming resets lastTime so the time you spent paused is not simulated. A long stall is clamped: without maxFrameSeconds, a tab that was in the background for ten seconds would try to run 600 updates in a single frame, freezing the page ("spiral of death").

The render callback receives alpha, the fraction of a step left over in the accumulator. A smooth renderer can interpolate between the previous and current state with it, which prevents jitter when the display rate and the update rate do not line up.

Stage 3: drawing to a canvas-shaped context

The renderer turns a particle list into drawing commands. It needs only a handful of methods from CanvasRenderingContext2D, so we describe those and give the editor a recording stand-in.

TypeScript Stage 3: rendering particles with a fading effect

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

A real browser needs only the glue. A CanvasRenderingContext2D already has every member of Context2DLike, and requestAnimationFrame fits Scheduler after a one-line wrapper. Here is the complete wiring, combining all three stages:

TypeScript
const canvas = document.querySelector<HTMLCanvasElement>('#stage');
const ctx = canvas?.getContext('2d');

if (canvas && ctx) {
  const scheduler: Scheduler = {
    request: (cb) => requestAnimationFrame(cb),
    cancel: (handle) => cancelAnimationFrame(handle),
  };

  const random = Math.random;
  let particles: Particle[] = [];

  const loop = new AnimationLoop(
    scheduler,
    (dt) => {
      if (random() < 0.5) particles.push(...spawnFountain(random, vec(canvas.width / 2, canvas.height - 10), 2));
      particles = stepWorld(particles, world, dt);
    },
    () => renderParticles(ctx, particles, canvas.width, canvas.height),
  );

  loop.start();

  document.addEventListener('visibilitychange', () => {
    if (document.hidden) loop.pause();
    else loop.start();
  });
}

Note the last lines: pausing when the tab is hidden saves battery. Browsers already throttle requestAnimationFrame in background tabs, but an explicit pause also stops your simulation from running at a different pace than the clock.

Ideas to extend it

  • Add emitters as a type: { kind: 'fountain' } | { kind: 'explosion'; power: number } with an exhaustive spawn function.
  • Make particles react to the pointer: add an attraction force toward the mouse position.
  • Use object pooling (reuse particle objects) to avoid garbage collection pauses with thousands of particles.
  • Handle high-DPI screens: scale the canvas by devicePixelRatio and use ctx.scale.
  • Draw trails by filling the canvas with a translucent color instead of clearing it.
  • Move the simulation to a Web Worker with OffscreenCanvas (see Typing APIs for typing messages).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is velocity stored in pixels per second and multiplied by dt?

    Scaling by elapsed time makes simulated speed independent of how often frames are produced.
  2. 2. What problem does the fixed time step with an accumulator solve?

    The simulation always advances in equal slices, so a slow frame means several updates, not one huge unstable one.
  3. 3. Why is the elapsed time per frame clamped to maxFrameSeconds?

    Without a clamp, a ten-second stall would trigger hundreds of updates in a single frame.
  4. 4. Why inject a Scheduler interface instead of calling requestAnimationFrame directly?

    A manual scheduler makes the loop deterministic and testable without a browser.
  5. 5. What does the alpha value passed to render represent?

    It is the leftover time divided by the step size, a number from 0 up to (but not including) 1.

Summary

  • Separate simulation (pure functions on readonly data), loop (timing) and rendering (drawing commands).
  • Express speeds per second and multiply by dt so motion does not depend on frame rate.
  • Use a fixed time step with an accumulator, and clamp long frames to avoid a spiral of death.
  • Inject a Scheduler and a Context2DLike so the code runs and tests without a browser.
  • Pause the loop when it is not needed, such as when the tab is hidden, and reset the clock on resume.

Next: Project: React Quiz with TypeScript