Interactive Vision From Zero · Episode 02

Hello, Hand Landmarks

Hello, Hand Landmarks is Episode 02 of Interactive Vision From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.

Part of the MasterAllArts Creative 3D Roadmap .

Episode 02 · Interactive Vision From Zero

Last episode, a single video frame was about 900,000 numbers — a grid of red, green, and blue values so dense you could drown a GPU in it just to ask "is there a hand in here?" This episode performs a magic trick: we take that same hand and collapse the entire thing down to 21 little dots. Twenty-one (x, y, z) triples. Sixty-three numbers, total. And here's the promise that carries the whole series — from this point on, everything we build reads those 21 numbers, never the pixels again.

Pinch detection, swipe gestures, drawing in the air, a hand that controls a 3D scene — all of it is just arithmetic on these 21 points. Below is a glowing skeleton tracking a hand in real time. Right now it's a synthetic hand, animated by math, so the page is alive the instant it loads with no webcam and nothing downloaded. Move your mouse over it to puppet the palm. When you're ready, click use my camera and the exact same skeleton snaps onto your real hand — because the code downstream of the dots can't tell the difference.

0 fps
move your mouse to puppet the hand
🔒 runs on-device · nothing leaves your machine
MediaPipe Hands · 21 landmarks
Just the wrist and five fingertips — six dots is already a recognizable hand.

🔒 The camera button runs the model entirely in your browser. No frame is ever uploaded; nothing leaves your machine. Until you press it, the demo uses a synthetic hand and makes zero network requests.

What you're looking at

Six dots, or twenty-one, floating on black, wired together into a hand. That's the end state of hand landmark detection: a model looks at an image and returns a fixed-size list of named points — the wrist, each knuckle, each fingertip. The picture is gone. What's left is a tiny, structured skeleton that means the same thing whether your hand fills the frame or sits in a corner, whether the lighting is warm or cold, whether you're you or someone else.

That compression is the entire reason this field is tractable. You do not write gesture logic against a million pixels that change every frame; you write it against 21 points that are already "the hand." Step the stage dropdown through the six views below and watch the same machine reveal itself one layer at a time. Toggle show labels to see the index numbers, and show depth (z) to see the third coordinate come alive as the hand leans toward and away from the camera.

The 21-point model

MediaPipe's hand landmarker always returns the same 21 points in the same order, regardless of pose. Index 0 is the wrist; then each finger contributes four points, thumb first, running from the knuckle out to the tip. Memorize this map — it never changes, and every episode after this one indexes into it:

0 WRIST 1 THUMB_CMC 2 THUMB_MCP 3 THUMB_IP 4 THUMB_TIP 5 INDEX_MCP 6 INDEX_PIP 7 INDEX_DIP 8 INDEX_TIP 9 MIDDLE_MCP 10 MIDDLE_PIP 11 MIDDLE_DIP 12 MIDDLE_TIP 13 RING_MCP 14 RING_PIP 15 RING_DIP 16 RING_TIP 17 PINKY_MCP 18 PINKY_PIP 19 PINKY_DIP 20 PINKY_TIP

Two subsets do most of the work in the whole series. The fingertips are 4, 8, 12, 16, 20, and the MCP knuckles (the base of each finger, where it meets the palm) are 2, 5, 9, 13, 17. Stage 1 draws only the bare minimum — the wrist plus the five tips — and your eye still reads it as a hand. That's the headline: six well-chosen dots already carry the gesture. The other fifteen just make it precise.

Stage 1 — Wrist + 5 fingertips

The minimal hand: indices 0, 4, 8, 12, 16, 20. Six dots. Notice how little you need before the brain fills in a hand — this is why fingertip-only tricks (pinch, point, swipe) are so cheap to build. We're drawing nothing but circles at six positions, yet the pose is unmistakable.

Stage 2 — All 21 points

Now every landmark, the full cloud. The extra fifteen points are the inner joints: the two or three knuckles along each finger and the base of the thumb. With all 21 you can measure how bent a finger is, not just where it ends — the difference between "pointing" and "curled" lives in these middle joints.

Stage 3 — Connections (the skeleton)

Dots become a hand when you draw the bones between them. There's a standard edge list, HAND_CONNECTIONS, that says which landmarks are joined: each finger is a chain from the wrist outward, plus one edge across the palm base. Draw those lines first, then the joints on top, and you get the glowing skeleton. This connection list is the same one MediaPipe ships, so your drawing code is real, not a toy.

Stage 4 — Labeled 0–20

Toggle show labels (this stage turns them on for you) and each dot is numbered. This is the single most useful debugging view in the series: when a gesture misfires, you label the points and instantly see that, say, index 8 isn't where you thought. Memorizing the map is good; being able to see it on a live hand is better.

Stage 5 — Normalized → pixel

This stage exposes the coordinate space directly. The model does not return pixels. It returns normalized coordinates: x and y in [0, 1], where (0, 0) is the top-left of the image and (1, 1) is the bottom-right. To draw, you multiply by the canvas size. The readout in this stage shows the index fingertip's raw normalized values and the live multiplication into pixels — watch x · width and y · height update as the hand moves. Get this conversion wrong and every point collapses into the top-left corner, because values under 1.0 are sub-pixel.

Stage 6 — Depth (z)

Each landmark has a third coordinate, z — roughly how far the point is from the camera, in about the same units as x. More negative means closer. This stage encodes z as both radius and brightness: a point leaning toward the camera grows and glows; one leaning away shrinks and dims. In synthetic mode the hand gently tilts so you can see the effect ripple across the fingers. It's only 2.5D — z is a relative hint, not a measured distance in meters — but it's enough to know which fingertip is in front.

How the code works

The beautiful part of this architecture is that one drawing function serves both the synthetic hand and the real camera. Both produce the identical structure — an array of 21 {x, y, z} objects in normalized space — so a single onLandmarks(hand) path renders either one. Let's walk the four pieces that matter.

(a) The connection list and the draw loop

Here's the canonical edge list, and the render: bones first, then joints on top. The one subtlety is the mirror flip. This is a selfie view, so we map x to the screen as (1 - lm.x) * width — without the flip, moving your hand right would move the on-screen hand left, the number-one source of "why is it backwards?" We apply the same flip to the synthetic hand so both modes agree.

// The standard 21-point edge list — which landmarks are bones.
const HAND_CONNECTIONS = [
  [0,1],[1,2],[2,3],[3,4],            // thumb
  [0,5],[5,6],[6,7],[7,8],            // index
  [5,9],[9,10],[10,11],[11,12],       // middle
  [9,13],[13,14],[14,15],[15,16],     // ring
  [13,17],[17,18],[18,19],[19,20],     // pinky
  [0,17],                             // palm base
];

// ONE path for synthetic + camera. hand = 21 normalized {x,y,z}.
function onLandmarks(hand) {
  ctx.clearRect(0, 0, W, H);
  const px = (lm) => [(1 - lm.x) * W, lm.y * H];   // ← mirror flip on X

  if (stage >= 2) {                              // bones first
    ctx.lineWidth = 3; ctx.strokeStyle = '#38bdf8';
    for (const [a, b] of HAND_CONNECTIONS) {
      const [ax, ay] = px(hand[a]), [bx, by] = px(hand[b]);
      ctx.beginPath(); ctx.moveTo(ax, ay); ctx.lineTo(bx, by); ctx.stroke();
    }
  }
  for (const i of visiblePoints) {            // then joints on top
    const [x, y] = px(hand[i]);
    ctx.beginPath(); ctx.arc(x, y, dotSize, 0, 7); ctx.fill();
  }
}

(b) Loading the real model — lazily

MediaPipe is never imported at the top of the file. If it were, the page would hit the network on every load and break offline. Instead we import() it dynamically, the first time the user clicks the camera button, wrapped in try/catch so any failure (no webcam, denied permission, file://) falls back to the synthetic hand instead of throwing.

const MP_URL  = 'https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.18';
const MP_WASM = MP_URL + '/wasm';
const HAND_TASK = 'https://storage.googleapis.com/mediapipe-models/' +
  'hand_landmarker/hand_landmarker/float16/1/hand_landmarker.task';

async function enableCamera() {
  try {
    setStatus('loading model… (first time downloads ~7 MB)');
    const { HandLandmarker, FilesetResolver } = await import(MP_URL);
    const fileset = await FilesetResolver.forVisionTasks(MP_WASM);
    landmarker = await HandLandmarker.createFromOptions(fileset, {
      baseOptions: { modelAssetPath: HAND_TASK, delegate: 'GPU' },
      runningMode: 'VIDEO', numHands: 1,
    });
    const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user' } });
    video = document.createElement('video');
    video.srcObject = stream; video.playsInline = true; await video.play();
    usingCamera = true;
    setStatus('camera live · on-device, nothing uploaded');
  } catch (err) {
    setStatus('camera unavailable — staying on synthetic (' + err.name + ')');
    usingCamera = false;     // graceful fallback; demo keeps running
  }
}

(c) Detecting per frame — and guarding null

In the render loop, if the camera is live we call detectForVideo with the current timestamp. When your hand leaves the frame, MediaPipe returns an empty landmark list — so res.landmarks?.[0] is undefined. We coalesce that to null and simply skip drawing that frame. Forgetting this guard is the classic crash: you index into hand[0].x and it's gone.

function tick(t) {
  let hand;
  if (usingCamera && landmarker && video.readyState >= 2) {
    const res = landmarker.detectForVideo(video, performance.now());
    hand = res.landmarks?.[0] || null;   // null when no hand in frame
  } else {
    const pos = mouseActive ? mousePos : autoPos(t * 0.001);
    hand = syntheticHand(t * 0.001, pos, poseOpts);
  }
  if (hand) onLandmarks(hand);          // guard: skip the frame if tracking is lost
  requestAnimationFrame(tick);
}

(d) The normalized → pixel helper

The one conversion you will write a thousand times. Normalized in, pixels out, with the mirror flip baked in so callers never forget it. Stage 5's readout is just this function with its inputs and outputs printed.

// normalized [0,1] → canvas pixels, mirrored on X for the selfie view.
function toPixel(lm, width, height) {
  return {
    x: (1 - lm.x) * width,    // flip: hand-right → screen-right
    y: lm.y * height,            // y is not flipped; down stays down
    z: lm.z,                     // relative depth, carried through untouched
  };
}

Common pitfalls

  • The hand is mirrored / backwards. You drew with raw lm.x * width and skipped the flip. In a selfie view you want (1 - lm.x) * width so your real hand and its skeleton move together. Apply it in both modes or synthetic and camera will disagree.
  • Everything bunches in the top-left corner. You forgot to scale by the canvas size. Normalized coordinates are in [0, 1]; an x of 0.5 is half a pixel, not the middle of the screen. Always * width and * height.
  • It crashes when the hand leaves the frame. MediaPipe returns an empty array, not the last pose. Coalesce res.landmarks?.[0] to null and guard before drawing — don't index into a missing hand.
  • The first second after clicking the camera is dead. The model file (~7 MB) is downloading. That's expected on a cold load; show a "loading model…" status so it doesn't look frozen. It's cached afterward.
  • You treat z as meters. It isn't. z is a relative depth hint in roughly x-units, good for "which fingertip is in front," not for measuring distance. Use it for ordering and scale, never for real-world geometry.

Exercises

  1. Color each finger. Give the five fingers five distinct hues by checking which chain (from HAND_CONNECTIONS) each landmark belongs to, and color its dots and bones to match. Suddenly the skeleton reads like a rainbow glove.
  2. Fill the palm. Draw a filled polygon through the MCP landmarks — 0 → 5 → 9 → 13 → 17 → 0 — to shade in the palm. You've turned five points into a surface, and the hand stops looking like wireframe.
  3. Bounding box. Loop over all 21 points, track min/max of the pixel x and y, and stroke a rectangle around the hand. Display its width and height. That box is the start of "where is the hand on screen," which you'll reuse for hit-testing later.

What's next

Episode 03 — The Pinch. We take just two of these 21 dots — the thumb tip (4) and the index tip (8) — measure the distance between them, and turn that single number into our first real gesture. It's the "hello world" of hand interaction, and it's where the 21-point model stops being a diagram and starts being a controller.