Interactive Vision From Zero · Episode 03

The Pinch

The Pinch is Episode 03 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 03 · Interactive Vision From Zero

The pinch is the click of spatial computing. On a Vision Pro you don't reach out and poke a button — you look at it and quietly touch your thumb to your index finger, and the whole interface responds. Every slick AR demo you've ever scrolled past is built on this one gesture. It's the mouse-down of the next decade, and it's just two fingertips finding each other in the air.

In about thirty lines we'll build a pinch detector that actually holds up: one that fires whether your hand is six inches or six feet from the camera, that never flickers at the edge of the threshold, and that throws off a satisfying ripple every single time it triggers. The trick is two ideas stacked together — normalize by hand size so distance stops mattering, then add hysteresis so the boundary stops chattering. Get those right and you have a primitive clean enough to reuse for the rest of the series. We literally do, in Episodes 04 and 06.

0 fps
hold mouse button to pinch · move to puppet the hand
🔒 runs on-device · nothing leaves your machine
pinch = dist(4,8) / handSize
Thumb tip (4) and index tip (8), a live line, and the raw pixel distance between them.

What you're looking at

That's a hand — synthetic, drawn from the same 21-landmark structure MediaPipe produces, so every line of detector code below runs unchanged on a real webcam. It's alive on first paint with no camera: the palm drifts along a slow path, and the thumb and index finger oscillate open and closed on their own so the demo keeps pinching itself. Move your mouse to puppet the hand around; hold the mouse button to force a pinch yourself. When you're ready for the real thing, hit use my camera and the exact same code starts reading your actual hand.

One convention to call out up front, because it's the number-one source of "why is it backwards" confusion: this is a selfie view, so we mirror the X axis. On screen we plot every landmark at (1 - x) * width, and we apply that same flip to the synthetic hand, so moving your hand (or mouse) right moves the on-screen hand right. Camera and synthetic modes stay in lockstep.

The badge in the corner is the whole episode in one line: pinch = dist(4, 8) / handSize. Everything below is just earning the right to write that and trust it. Step through the six stages with the dropdown.

Stage 1 — Thumb and index, and a line between them

We start with the two landmarks that matter: thumb tip is index 4, index tip is index 8 (memorize those — they're the canonical pinch pair forever). We draw a dot on each, a live line connecting them, and a readout of the raw distance in pixels. Watch the number breathe as the synthetic fingers open and close. Simple, and it looks like it works. It does not work, and the next stage shows exactly why.

Stage 2 — Raw distance fails

Here the synthetic hand's scale oscillates: it walks toward and away from the camera while the fingers hold a fixed gap. Watch the raw pixel distance. It swings wildly — large when the hand is "near," small when it's "far" — even though the fingers aren't moving relative to each other. If you pick any fixed pixel threshold for "pinch," it'll trigger constantly when the hand is far and never when it's near. Raw distance conflates the gesture with the camera distance. Useless as-is.

Stage 3 — Normalize by hand size

The fix is to measure the pinch in units of the hand itself. We pick a span that scales with the whole hand — here the wrist (0) to the middle-finger knuckle (middle-MCP, 9) — and divide the thumb-index distance by it. When the hand doubles in apparent size, both the numerator and the denominator double, and the ratio stays put. Toggle to this stage with the scale still oscillating: the raw number (greyed out) keeps swinging, but the normalized value barely moves. That ratio is now scale-invariant. It's a pure number around 1.0 when the fingers are apart and near 0 when they touch — and it means the same thing at any distance.

Stage 4 — One threshold, and the flicker problem

Now turn the ratio into a boolean: isPinching = normalized < threshold. Drag the threshold slider until the line sits right at the boundary while the fingers hover near it. The state machine-guns: pinch / not / pinch / not, several times a second. Raw landmarks are noisy, and a single threshold has zero tolerance — the tiniest jitter across the line flips the output. A UI built on this would fire phantom clicks and drop real ones. One threshold is never enough.

Stage 5 — Hysteresis (a Schmitt trigger)

This is the key lesson of the episode. Instead of one threshold we use two: a lower close threshold and a higher open threshold, separated by the hysteresis gap. You have to drop below the close line to start a pinch, and rise above the higher open line to end it. In between, the output simply holds its last state. That dead-band is exactly what kills the flicker. This pattern — two thresholds with memory — is a Schmitt trigger, and it's everywhere in electronics for precisely this reason. Drag the gap to 0 and the flicker returns; widen it and the gesture gets rock-solid (too wide and it feels laggy). The two threshold lines are drawn so you can see the dead-band.

Stage 6 — Fire an event

A stable boolean is good; a stable edge is what you actually wire UI to. The detector reports justPressed the single frame the pinch closes and justReleased the frame it opens. On every justPressed we spawn a ripple at the midpoint between the two fingertips and bump a counter. Pinch with the mouse, or just watch the auto-pinch fire: each close throws one clean ripple, never a burst of phantoms. That edge — not the held state — is the reusable click of the whole series.

How the code works

The detector is small enough to read in one sitting. Four pieces: a distance + normalization helper, a hysteresis state machine, the wiring that turns a press into a ripple, and the one fact that makes the whole series hang together — synthetic and camera feed the exact same function.

(a) Distance, and normalizing by hand size

Euclidean distance between two landmarks is just Pythagoras. We work in normalized [0,1] landmark space (not pixels), so the ratio is resolution-independent too. Hand size is the wrist→middle-MCP span; you could equally use palm width (index-MCP→pinky-MCP) — any length that scales with the hand works.

// landmarks are MediaPipe's: 21 of {x, y, z}, x/y normalized to [0,1]
const dist = (a, b) => Math.hypot(a.x - b.x, a.y - b.y);

function pinchRatio(lm) {
  const fingers  = dist(lm[4], lm[8]);   // thumb tip ↔ index tip
  const handSize = dist(lm[0], lm[9]);   // wrist ↔ middle knuckle
  return fingers / (handSize || 1e-6);   // scale-invariant, ~0 when pinched
}

(b) The hysteresis state machine

This is the reusable core. It owns one bit of state — isPinching — and each frame decides whether to flip it, using the two thresholds. It returns a tidy struct so callers never touch the internals. justPressed and justReleased are computed by diffing against last frame's state, which is how we catch fast pinches that a polling check would miss.

// close < open. You must cross BELOW close to grab, ABOVE open to let go.
function makePinchDetector(close = 0.40, open = 0.48) {
  let isPinching = false;
  let smooth = 1;                       // optional jitter smoothing
  return function update(lm) {
    const raw = pinchRatio(lm);
    smooth += (raw - smooth) * 0.5;     // light lerp; 1.0 = off
    const was = isPinching;
    if (!isPinching && smooth < close) isPinching = true;   // grab
    else if ( isPinching && smooth > open ) isPinching = false;  // release
    return {
      value: smooth,
      isPinching,
      justPressed:  isPinching && !was,
      justReleased: !isPinching && was,
    };
  };
}

(c) Wiring a press to a ripple

The detector knows nothing about graphics — it just reports edges. We act on them. Notice we read justPressed, not isPinching: that's the difference between one ripple per pinch and a new ripple every single frame the fingers stay closed.

const detector = makePinchDetector(close, open);
let pinchCount = 0;

function onLandmarks(lm) {
  const p = detector(lm);
  if (p.justPressed) {                 // the click edge
    const mx = (lm[4].x + lm[8].x) / 2;   // midpoint between the tips
    const my = (lm[4].y + lm[8].y) / 2;
    spawnRipple(mx, my);
    pinchCount++;
  }
  // p.value / p.isPinching drive the meter + readouts
}

(d) Same struct for synthetic and camera

The detector takes landmarks and returns a struct. It has no idea whether those 21 points came from a math function or a neural net reading your webcam. That's the whole architecture of the series: one onLandmarks(hand) path, fed by whichever source is live. Swapping the camera on changes the data source and nothing downstream.

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 pinch = 0.5 + 0.5 * Math.sin(t * 1.6); // auto-pinch oscillation
    hand = syntheticHand(t, mouseActive ? mousePos : autoPos(t), { pinch });
  }
  if (hand) onLandmarks(hand);            // ONE downstream path for both
}

Common pitfalls

  • Not normalizing. A raw pixel (or raw normalized) distance changes with how close the hand is to the camera. Always divide by a hand-relative span (wrist→middle-MCP, or palm width) so the gesture means the same thing near and far. Skip this and your threshold only works at one exact distance.
  • One threshold instead of hysteresis. A single cutoff flickers the instant the value sits near it — and it always will, because landmarks are noisy. Use two thresholds (a Schmitt trigger): cross below close to engage, above open to release. The gap between them is your noise immunity.
  • Wrong landmarks. The pinch pair is the tips: thumb is 4, index is 8. It's easy to grab a knuckle (MCP) by mistake and get a distance that barely changes when you pinch.
  • Raw jitter. Even normalized, the ratio shimmers a little. A light lerp toward the new value each frame (smooth += (raw - smooth) * 0.5) takes the edge off without adding real lag. Don't over-smooth or the gesture feels mushy.
  • Polling the held state and missing fast pinches. If you only ever check isPinching, a quick tap that opens and closes between two of your checks vanishes. Use edge detection — justPressed / justReleased — so every transition is caught exactly once.
  • Camera only works on localhost / HTTPS. Opening the file via file:// silently blocks getUserMedia. The synthetic demo still runs fine; just serve over localhost to try the webcam.

Exercises

  1. Add a second pinch for "right click." Build a second detector on the thumb tip (4) and middle tip (12). Now you have two independent gestures — index-pinch as left click, middle-pinch as right click. Mind that they don't trigger each other when fingers bunch together; tune each one's thresholds separately.
  2. Tune hysteresis live and find your own flicker-free gap. Park the fingers right at the threshold and slowly widen the gap slider from 0. Note the exact value where the chatter stops — that's the noise floor of your input. Real webcam data usually needs a wider gap than the clean synthetic hand; measure both.
  3. Log pinch duration to tell a tap from a hold. Stamp the time on justPressed, subtract on justReleased. Under ~200 ms is a tap; longer is a hold. That one number unlocks tap-vs-press-and-hold, the foundation of drag, long-press menus, and the grab you'll build next.

What's next

Episode 04 — Grab and Throw. The pinch stops being a click and becomes a grip. We hand this exact detector to a little physics world: on justPressed you grab a ball, while pinched you drag it, and on justReleased you let go — with whatever velocity your hand was carrying, so you can wind up and throw it across the screen. Same struct, same edges, now with momentum. It's the most fun ten lines in the series, and it leans entirely on the clean detector you just built. (If you want to see where the thrown ball's bounce comes from, it's the same Three.js physics the Three.js series sets up.)