Interactive Vision From Zero · Episode 06

Control the DOM With Your Hand

Control the DOM With Your Hand is Episode 06 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 06 · Interactive Vision From Zero

This is the episode where it stops being a tech demo and starts feeling like Minority Report. You point at the screen, a glowing ring follows your fingertip, you pinch in the air — and an actual button clicks. Not a canvas drawing of a button. A real <button>, in the real DOM, with a real event. Pinch a card and drag it across the page. Pinch the slider and slide it. The whole web, driven by a finger you're waving in front of a webcam.

The trick is almost embarrassingly simple, and it's the secret behind every "control a website with your hands" video you've seen: smooth the index fingertip into page pixels, ask the browser document.elementFromPoint(x, y) what's under it, and turn a pinch into press / drag / release. That's it. The demo below is a tiny working app — cards, a button, a slider, a scrollable list — and it's already playing itself with a synthetic hand. No camera needed to watch it work; flip yours on when you want to take the controls.

0 fps
move your mouse to puppet the hand · or hit “use camera”
 handos — drag, click, slide. all by pinch.
synthetic · autoplay
fingertip(8) → DOM cursor
A smoothed ring tracks the index fingertip. Jitter is the enemy — we filter it hard.

🔒 runs on-device · nothing leaves your machine. The synthetic hand needs no camera at all; the camera path is loaded only when you ask for it.

What you're looking at

Everything inside the dark frame above is ordinary HTML: four .card divs, a <button> with a counter, a custom .slider, and a scrollable .list. There is no Three.js here — just the DOM and one glowing cursor div. A synthetic hand (the same 21-landmark structure MediaPipe emits) runs a scripted loop: it floats to a card, pinches, drags it, lets go; floats to the button and pinches to click; then nudges the slider. The fingertip is landmark 8 (INDEX_TIP), and we map it — mirrored — into pixels inside the frame.

Because the page is mirrored (selfie view), we flip X when we convert a landmark to a pixel: x = (1 - lm.x) * width. Move your hand right, the cursor goes right. Forget that flip and the whole UI feels possessed — it's the number-one "why is it backwards" bug in the series.

Stage 1 — The cursor follows your fingertip

The foundation. We take landmark 8, convert it to pixels, and move the ring there. But raw landmarks shimmer — even a perfectly still hand jitters a few pixels every frame from sensor noise. A jittery cursor is a useless cursor: you can't aim it at a 12-pixel slider knob if it's vibrating. So we never draw the raw point. We draw a heavily smoothed point, an exponential moving average that lags slightly but lands rock-steady. Drag the smoothing slider to 0 to feel the noise, then back to 0.78 to feel why every hand-UI smooths hard.

Stage 2 — Hover highlight via elementFromPoint

Now the cursor knows what it's pointing at. Each frame we call document.elementFromPoint(px, py) — a built-in that returns the topmost element at those screen coordinates — and add a .hot class to it (and remove it from whatever we left). Cards glow, the button brightens, the slider lights up. This is your hover state, and it's the proof that a fingertip is now a genuine pointing device. (Critical gotcha, see below: the cursor ring itself must be pointer-events:none, or elementFromPoint just returns the cursor every time.)

Stage 3 — Pinch = click

We reuse the pinch detector from Episode 03: the normalized distance between the thumb tip (4) and index tip (8), with hysteresis — it engages at the threshold but won't release until the fingers open noticeably wider, so it never flickers mid-pinch. A pinch down while hovering the button presses it; the pinch up releases — and because the cursor didn't travel far between down and up, we treat it as a click. The counter ticks up. Watch the synthetic hand do it on loop.

Stage 4 — Pinch-drag a card

Same gesture, different outcome. Pinch down on a card and we remember which one and where you grabbed it. While the pinch holds, every cursor move updates the card's transform: translate(...) so it sticks to your fingertip. Release and it stays put. The make-or-break detail is click vs drag: if the cursor moved more than a few pixels between down and up, it's a drag (do nothing on release); if it barely moved, it's a click. One gesture, disambiguated by distance — exactly how a real mouse works.

Stage 5 — Slide & scroll

The slider and the list use the very same press/drag machine. Pinch the slider knob and move sideways: we map the cursor's X within the track to a 0–100 value and recolor a swatch live. Pinch anywhere on the list and move vertically: we translate the list's inner track to scroll it (clamped so it can't fly off). A two-hand spread would do the same scroll — here one pinched hand dragging vertically stands in for it, which is all "scroll" ever needs to be.

Stage 6 — The full mini-app

Everything live at once. Hover to highlight, pinch to grab, drag cards anywhere, click the button, work the slider, scroll the list — with one hand, no mouse, no keyboard. This is the whole point of the series cashed out in one screen: a hand in the air is now a complete pointing device for a real interface.

How the code works

1 · Fingertip → page pixels, then smooth it hard

Landmark 8 is normalized to [0,1]. We mirror X, scale into the frame's pixel box, and run it through an exponential smoother. a is the smoothing amount: 0 is raw and twitchy, 0.8+ is buttery. (A One-Euro filter is the fancy upgrade — adaptive so fast moves stay responsive — but a plain EMA is plenty to make a UI usable, and it's two lines.)

// landmark 8 (INDEX_TIP), normalized [0,1] → pixels inside the demo box
const rect = demo.getBoundingClientRect();
const tip  = hand[8];
const rawX = (1 - tip.x) * rect.width;   // (1 - x) = mirror, selfie view
const rawY = tip.y * rect.height;

// exponential moving average — the single most important line for a usable cursor
const a = smoothing;                       // 0 = raw/jittery, ~0.8 = steady
cur.x = cur.x + (rawX - cur.x) * (1 - a);
cur.y = cur.y + (rawY - cur.y) * (1 - a);
cursorEl.style.transform = `translate(${cur.x}px, ${cur.y}px)`;

2 · Hit-test with elementFromPoint

One built-in does all the work. It takes viewport coordinates, so we add the demo box's offset back on. And the cursor ring is pointer-events:none — otherwise it sits on top of everything and the hit-test only ever finds the cursor itself.

// cur.x/cur.y are relative to the demo box; elementFromPoint wants viewport coords
const el = document.elementFromPoint(rect.left + cur.x, rect.top + cur.y);

// hover highlight: move the .hot class from the old target to the new one
if (el !== hovered) {
  hovered?.classList.remove('hot');
  if (el && el.closest('.card,.btn,.slider,.list')) {
    hovered = el.closest('.card,.btn,.slider,.list');
    hovered.classList.add('hot');
  } else hovered = null;
}

3 · The pinch → press / drag / click state machine

This is the heart of it. A pinch edge (open→closed) is a press on whatever's under the cursor; while held we drag; the release edge (closed→open) is either a click (if the cursor barely moved) or just the end of a drag. The distance check is the click-vs-drag disambiguation, and a tiny time guard debounces accidental double-fires.

const pinchNow = pinching;                  // from the hysteresis detector below

if (pinchNow && !pinchPrev) {                // ── PRESS edge ──
  down = { x: cur.x, y: cur.y, t: now };
  target = el?.closest('.card,.btn,.slider,.list') || null;
  target?.classList.add('grabbed');       // or .pressed for the button
}
else if (pinchNow && pinchPrev && target) { // ── DRAG (held) ──
  if (target.matches('.card'))   moveCard(target, cur);
  if (target.matches('.slider')) setSlider(cur);
  if (target.matches('.list'))   scrollList(cur);
}
else if (!pinchNow && pinchPrev) {          // ── RELEASE edge ──
  const moved = Math.hypot(cur.x - down.x, cur.y - down.y);
  if (moved < 10 && now - lastClick > 250) {  // barely moved + debounced = CLICK
    target?.dispatchEvent(new MouseEvent('click', { bubbles: true }));
    lastClick = now;
  }
  target?.classList.remove('grabbed'); target = null;
}
pinchPrev = pinchNow;

4 · Pinch detection with hysteresis, and dragging via transform

The detector (ported from Ep03) measures thumb-tip↔index-tip distance, normalized by hand size so it's scale-independent, and uses two thresholds so it can't chatter. Dragging is just writing a new translate() each frame — cheap, GPU-composited, 60fps.

// scale-independent pinch distance: thumb tip (4) vs index tip (8), over hand span
const span = dist(hand[0], hand[9]);              // wrist→middle-MCP = hand size
const d    = dist(hand[4], hand[8]) / span;        // normalized
// HYSTERESIS: engage tight, release loose → no flicker at the boundary
if (!pinching && d < thresh)        pinching = true;
if ( pinching && d > thresh * 1.7)  pinching = false;

// dragging a card = remember the grab offset, then follow the cursor
function moveCard(card, cur) {
  card.x = cur.x - grab.dx;  card.y = cur.y - grab.dy;
  card.style.transform = `translate(${card.x}px, ${card.y}px)`;
}

Common pitfalls

  • Jitter makes it unusable. Raw landmarks shimmer; an unsmoothed cursor can't hit a small target. Smooth heavily (EMA at ~0.8, or a One-Euro filter). This is the first thing to get right — set the slider to 0 in the demo to see the disease.
  • The cursor hit-tests itself. If the cursor element isn't pointer-events:none, elementFromPoint returns the cursor on every call and nothing under it ever highlights. This bites everyone once.
  • Click vs drag ambiguity. A pinch-release after moving 80px is a drag, not a click — fire click only when the travel since press is under a small threshold (~10px here). Skip this and dragging a card also "clicks" wherever you drop it.
  • Coordinate spaces. Landmarks are normalized [0,1]; elementFromPoint wants viewport pixels; your transforms want box-relative pixels. Mixing them up bunches everything in the top-left. And mirror X (1 - x) or the UI feels backwards.
  • Accidental double-clicks. Tracking noise can produce two pinch edges in a few frames. Debounce: ignore a new click within ~250ms of the last one.
  • Lost tracking. When the hand leaves frame MediaPipe returns no landmarks — guard for null and (nicely) treat it as a forced pinch-release so a card isn't stuck to a hand that's no longer there.

Exercises

  1. Pinch-and-hold right-click. If a pinch is held still for ~500ms without moving, pop a small radial menu (a few divs in a circle around the cursor) and let a flick toward one select it. You've built a gesture-native context menu.
  2. Momentum scroll. Record the cursor's vertical velocity over the last few frames; on release, keep scrolling the list and decay the velocity each frame (v *= 0.92). Suddenly the list feels like a touchscreen.
  3. Throwable cards. Track velocity while dragging a card; on release, let it coast and bounce off the walls — a direct callback to the physics in Episode 04. Releasing while moving = a throw.

What's next

Episode 07 — Paint With Light. We stop clicking and start painting: instead of hit-testing the DOM, the fingertip leaves a trail of glowing particles — a comet of light that follows your hand. Same fingertip, same smoothing, brand-new feeling. The cursor becomes a brush.