Web Games From Zero · Episode 02

Sprites & Animation

Sprites & Animation is Episode 02 of Web Games From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.

Part of the MasterAllArts Creative 3D Roadmap .

Episode 02 · Web Games From Zero

You don't need an artist to make something move with personality. Everything in the demo below — the little fellow that idles, breathes, runs across the floor, leaps over a gap, and squashes when he lands — is drawn entirely in code. No PNGs, no sprite packs, no Photoshop. A handful of ellipses and rectangles, arranged by a few sines and cosines, and suddenly there's a guy in there with moods.

This episode is about the oldest trick in game graphics: the sprite — a small image stamped onto the screen — and the second-oldest trick, flipping between a few of them fast enough that your eye fills in the motion. We'll draw a character from shapes, bake a run cycle into a procedural sprite sheet, animate it on a clock that doesn't care about your monitor's refresh rate, flip it by direction, and pick the right animation — idle, run, or jump — straight from the character's velocity. He walks himself around until you grab the arrow keys.

0 fps
▶ playing demo — press any key (or ← → space) to take over
0 art assets · drawn in code
A character built from a capsule body and two eyes — no image files at all.

Step through the stages with the dropdown — each one is a numbered section below. Move with ← → (or A/D) and jump with Space / ↑ / W. Leave it alone for ten seconds and the demo takes the wheel again.

What you're looking at

One canvas, six stages, and a single character whose entire appearance is computed. Stage 1 is the raw drawing. Stage 2 reveals the sprite sheet we bake once at startup — a strip of run-cycle poses rendered to an offscreen canvas, shown overlaid so you can see the frames. Stages 3–6 use that sheet (and a couple of others) to bring him to life: cycling frames on a fixed clock, mirroring by facing direction, switching animations from velocity, and finally a layer of juice — a squash when he lands, an occasional blink, a crouch of anticipation before the jump.

The fps counter should hold near 60. The badge tracks the current frame and state so you can watch the machinery. None of this touches the network: the "art" is a few dozen ctx.fillRect and ctx.ellipse calls.

Stage 1 — A drawn character

A sprite doesn't have to come from a file. The cheapest sprite in the world is a function that takes a canvas context and paints a character at the origin. Ours is a capsule (a rounded body), a slightly lighter belly, two white eyes with dark pupils, and two little legs. That's it — but proportions and a soft palette do a surprising amount of work. A round body reads as "friendly" before it does anything at all.

The key discipline: draw in a local coordinate space centred on the character, from roughly (-16,-24) to (16,8), with the "ground contact" point at local y = 8. Then the caller translates to wherever the character is in the world and the same draw code works anywhere. We pass in a pose object — a few numbers like leg swing and squash — so the same function can produce every frame of every animation. One body, infinite poses.

Stage 2 — A procedural sprite sheet

Redrawing a character from a dozen shapes every frame is fine for one guy, but the classic technique is to draw each pose once, into an offscreen image, and then just blit (copy) the right rectangle each frame. That offscreen image is a sprite sheet: a grid of frames packed side by side.

We build ours at startup. Create an offscreen <canvas> frames × cellW wide, loop over the frames, and for each one compute a pose (here, a walk-cycle phase) and call the very same drawCharacter from Stage 1 into its cell. Stage 2 overlays that finished sheet so you can see all eight run frames laid out in a row — the exact strip a pixel artist would hand-draw, except we generated it from a formula. The win is twofold: drawing becomes a cheap copy, and the poses are guaranteed consistent because they all came from one function.

Stage 3 — Frame animation

Now we play the sheet. Animation is just choosing which cell to draw this instant. The naive version — "advance one frame every render frame" — is a bug: on a 144 Hz monitor your character animates almost three times faster than on a 50 Hz one. The fix is to drive the frame index off accumulated real time, not the render loop. Pick a frame rate for the animation (say 10 fps), accumulate elapsed seconds, and step the frame whenever you've banked 1/fps seconds. Identical motion on every machine.

Stage 4 — Flip by direction

Our run cycle faces right. To run left we don't draw new art — we mirror the existing sprite horizontally. The trick that trips everyone up: if you just set scale(-1, 1), the sprite flips around the canvas origin and flies off to the left. You have to flip around the character's own centre: translate to the character, scale X by -1 (or +1), then draw with the sprite centred on that origin. The character spins to face its travel direction in place, and one set of frames serves both ways.

Stage 5 — Animation states

A character usually has more than one animation: standing still, running, jumping. The elegant move is to derive the current state from physics rather than tracking it by hand. We look at two things — is he on the ground, and how fast is he moving horizontally — and choose: in the air ⇒ jump; grounded and moving ⇒ run; grounded and still ⇒ idle. The velocity already knows what he's doing; we just read it. Each state has its own little sheet (idle has a gentle breathe, jump is a stretched single pose), and the run animation's speed even scales with how fast he's actually moving.

Stage 6 — Polish & juice

The difference between "it animates" and "it's alive" is a few cheap touches. We add a squash on landing — the body flattens and rebounds, driven by a quick timer — a periodic blink where the eyes become lines for a few frames, and a crouch of anticipation just before a jump leaves the ground. None of these are new sprites; they're tiny modifications to the pose we already feed the draw function. That's the whole philosophy of this episode: a parametric character plus a clock gives you personality almost for free.

How the code works

Four pieces carry the episode: drawing the character, baking the sheet, the time-based frame timer, and the velocity-to-state selector. Here they are close to verbatim.

(a) Drawing the character procedurally

One function, drawn in a local space centred on the body, parameterised by a pose. Everything else — every frame, every state, every juicy squash — is just a different pose handed to this:

// Draw the character at the local origin (0,0). Feet rest at y = +8.
// pose = { legSwing, lean, squash, blink, arm }  — all small numbers.
function drawCharacter(ctx, pose) {
  const sx = 1 + pose.squash;        // squash & stretch: wider…
  const sy = 1 - pose.squash;        // …and shorter (volume-ish)
  ctx.save();
  ctx.scale(sx, sy);
  ctx.rotate(pose.lean);

  // legs — swing in opposition using the cycle phase
  ctx.fillStyle = '#1f6feb';
  for (const s of [-1, 1]) {
    const swing = pose.legSwing * s;
    ctx.beginPath();
    ctx.roundRect(s * 3 - 3, 2, 6, 9 + swing, 3);
    ctx.fill();
  }

  // body capsule
  ctx.fillStyle = '#58a6ff';
  ctx.beginPath();
  ctx.roundRect(-12, -22, 24, 30, 12);
  ctx.fill();

  // eyes — two whites, dark pupils; blink squashes them to slits
  const eh = 5 * (1 - pose.blink);
  for (const s of [-1, 1]) {
    ctx.fillStyle = '#fff';
    ctx.beginPath(); ctx.ellipse(s * 5, -10, 4, eh, 0, 0, 7); ctx.fill();
    if (pose.blink < 0.5) {
      ctx.fillStyle = '#0b1020';
      ctx.beginPath(); ctx.ellipse(s * 5 + 1, -10, 2, 2.4, 0, 0, 7); ctx.fill();
    }
  }
  ctx.restore();
}

Because the body is shape-based, scaling and rotating it for squash and lean is free and crisp — no resampling, no blur.

(b) Building the sprite sheet to an offscreen canvas

Bake every frame of a cycle once, into its own cell of an offscreen canvas. We pass a phase 0→1 through a pose generator so the eight frames form a smooth loop:

// Render `count` frames of a cycle into one offscreen strip.
function buildSheet(count, cellW, cellH, poseFor) {
  const sheet = document.createElement('canvas');
  sheet.width  = count * cellW;
  sheet.height = cellH;
  const sctx = sheet.getContext('2d');

  for (let i = 0; i < count; i++) {
    const phase = i / count;            // 0 … just under 1, loops cleanly
    sctx.save();
    // put the local origin at the cell's centre-ish (feet near the bottom)
    sctx.translate(i * cellW + cellW / 2, cellH - 14);
    drawCharacter(sctx, poseFor(phase));
    sctx.restore();
  }
  return { canvas: sheet, count, cellW, cellH };
}

// a run pose: legs swing as a sine of the phase, body bobs and leans
const runPose = (p) => ({
  legSwing: 7 * Math.sin(p * Math.PI * 2),
  lean: 0.12,
  squash: 0.06 * Math.sin(p * Math.PI * 4),
  blink: 0, arm: 0,
});

(c) The frame timer — advance on time, not on render frames

The single most important habit in animation. Accumulate elapsed seconds and step the frame index every 1/fps seconds, so a 144 Hz screen and a 50 Hz screen show the same motion:

const anim = { frame: 0, acc: 0 };

// called once per fixed update with the constant STEP (e.g. 1/60 s)
function tickAnim(sheet, fps, dt) {
  anim.acc += dt;
  const frameTime = 1 / fps;          // seconds each frame is held
  while (anim.acc >= frameTime) {     // may step 0, 1, or more
    anim.acc  -= frameTime;
    anim.frame = (anim.frame + 1) % sheet.count;   // wrap = loop
  }
}

// drawing the current frame is just copying one cell of the strip:
function drawFrame(ctx, sheet, frame, x, y, flip) {
  ctx.save();
  ctx.translate(x, y);
  ctx.scale(flip ? -1 : 1, 1);            // flip around the character centre
  ctx.drawImage(
    sheet.canvas,
    frame * sheet.cellW, 0, sheet.cellW, sheet.cellH,   // src cell
    -sheet.cellW / 2, -sheet.cellH, sheet.cellW, sheet.cellH // dst, centred
  );
  ctx.restore();
}

(d) The animation-state selector from velocity

Don't hand-manage a state variable — read it from the physics. The only subtlety is hysteresis: use a small speed threshold (and the grounded flag) so a character hovering near zero speed doesn't flicker between idle and run every frame:

// choose the animation purely from the body's motion
function pickState(body) {
  if (!body.grounded) return 'jump';        // in the air → jump/fall pose
  if (Math.abs(body.vx) > RUN_THRESH) return 'run';  // moving on ground → run
  return 'idle';                          // otherwise → idle
}

// RUN_THRESH is generous (e.g. 12 px/s) so near-zero jitter stays "idle".
// reset the frame counter when the state changes, so each anim starts at frame 0:
const state = pickState(body);
if (state !== anim.current) { anim.current = state; anim.frame = 0; anim.acc = 0; }

And, as everywhere in this series, all the movement that feeds body.vx and body.grounded happens inside a fixed-timestep update — the same loop from Episode 01. The animation reads physics; physics never reads the frame rate.

Common pitfalls

  • Animation tied to the render frame-rate. The classic bug: frame++ once per requestAnimationFrame. Your character then runs at 144 fps on a gaming monitor and 50 fps on an old laptop — same code, different speed. Always advance by accumulated time against a chosen frame rate, as in block (c).
  • Flip pivot gone wrong. A bare ctx.scale(-1, 1) mirrors around the canvas origin (0,0), so a flipped sprite jumps far to the left. translate to the character first, then scale, then draw with the sprite centred on the new origin. Flip around the centre, not the world.
  • State thrash. Choosing run vs idle on vx !== 0 makes the animation strobe whenever speed wobbles around zero (e.g. friction settling). Use a small threshold — or full hysteresis (different thresholds to enter and leave a state) — so the choice is stable.
  • Blurry sprites. When you scale a baked sheet up, the browser smooths it and pixel art turns to mush. Set ctx.imageSmoothingEnabled = false for a crisp pixel look — or, as we do here, draw the character as vector shapes so it stays sharp at any scale and DPR.
  • Resetting frames on every state read. Only reset anim.frame when the state actually changes (compare to the previous state). Resetting it unconditionally pins every animation to frame 0 and nothing moves.
  • Forgetting DPR on the offscreen sheet. The visible canvas is scaled by devicePixelRatio, but a sheet baked at 1× will look soft when blitted onto it. Bake the sheet at the same scale you draw, or keep it vector. (We keep the live character vector and only bake the sheet for the Stage 2 illustration.)

Exercises

  1. A "hurt" flash. Add a hurt timer that counts down; while it's positive, draw the character tinted white (set ctx.globalCompositeOperation = 'source-atop' and fill a rectangle over the sprite, or just swap the body colour) and add a quick shake. Trigger it on a key press. One more state, derived the same way as the others.
  2. One pose function to rule them all. Right now run, idle, and jump have separate generators. Refactor them into a single poseFor(state, phase) and build every sheet by passing that function to buildSheet from block (b). Fewer moving parts, and adding "hurt" or "wave" becomes a new branch in one place.
  3. A running trail. When |vx| is high, push the character's position into a short ring buffer and draw the last few entries as faint, semi-transparent ghosts behind him before drawing the real sprite. Cheap, and it sells speed instantly — a taste of the juice we pile on in Episode 05.

What's next

Episode 03 — Collision detection: make the world solid. Our character currently runs on an invisible floor we faked with a single if. Next we give the world real geometry — axis-aligned boxes, swept tests so fast movers don't tunnel through thin walls, and proper resolution so he can stand on platforms, bonk his head, and slide along walls. The animation states you built today (grounded drives idle/run/jump) plug straight into real collision, and the guy stops floating and starts living in a place.