moves / game dev / sprite sheet animation

Sprite sheet animation on canvas

Pack animation frames side by side in one image and draw one slice at a time with the 9-argument `drawImage`. Pick the frame from elapsed time, not a frame counter, so the animation plays at the same speed on every monitor.

#sprites#animation#canvas
ts
const sheet = new Image();
sheet.src = "/hero-run.png"; // 6 frames in one row, each 32×32

const SIZE = 32;
const FRAMES = 6;
const FPS = 10; // animation speed, independent of refresh rate

function drawHero(ctx: CanvasRenderingContext2D, x: number, y: number, timeMs: number) {
  const frame = Math.floor((timeMs / 1000) * FPS) % FRAMES;
  ctx.drawImage(
    sheet,
    frame * SIZE, 0, SIZE, SIZE, // source slice
    x, y, SIZE * 2, SIZE * 2,    // destination (2× scale)
  );
}

Related

WWADD — Moves. Stacks. Judgment calls.

FREE REFERENCE · NO LOGIN · NO TRACKING