Interactive Vision From Zero · Episode 18
Depth & WebXR Hand Tracking
Depth & WebXR Hand Tracking is Episode 18 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 .
For seventeen episodes a "hand" has been twenty-one flat dots — MediaPipe's
landmarks, normalized to the image, with a z we politely called a hint.
That's 2.5D: real enough to pinch, fake enough that depth wobbles. Put on a
headset and everything changes. The WebXR XRHand API hands you
twenty-five joints per hand, each one a full 3D transform in
room space — position, orientation, and a physical radius — measured by the device's
own cameras and IMU. Your real hands appear in the scene. No model to load,
no mirror math, no guessing depth.
You probably don't have a headset open in this tab, so the demo below is alive
anyway: a synthetic 3D articulated hand, all 25 joints, that you can
orbit and watch breathe. We'll step through the joint hierarchy, size the spheres by
their radii, measure a pinch in true 3D, and then look at the exact
frame.getJointPose() loop you'd run on-device. The Enter VR
button is gated on navigator.xr.isSessionSupported('immersive-vr') — if a
headset is there, it lights up; if not, it stays disabled and the synthetic hand keeps
running. That gate is the whole lesson in defensive XR.
🔒 Runs on-device · nothing leaves your machine. WebXR hand tracking is computed entirely on the headset; like our camera path in earlier episodes, no video and no landmarks are ever uploaded.
What you're looking at
A right hand, floating in 3D, rendered as spheres at every joint with thin bones between them. It's driven by a synthetic generator that emits the same 25-joint structure WebXR does — so the code you write against the demo is the code you'd run on a Quest. The hand drifts on a slow path and the fingers do a gentle breathing curl so there's always motion; grab it with the mouse and orbit to feel that this is genuinely volumetric, not a flat overlay. Like every demo in this series it's mirrored (selfie convention, X flipped) so a right hand reads as your right hand.
Stage 1 — A 3D hand, 25 joints
The rawest view: one sphere per joint, no bones. Count them and you'll find twenty-five, not twenty-one. Orbit it. Unlike a MediaPipe overlay — which is really a 2D drawing with a depth hint — every dot here has a true position in meters. The back of the hand occludes the palm; fingers pass in front of and behind each other correctly. That's the first thing depth buys you: real occlusion, for free.
Stage 2 — The joint hierarchy
Hands aren't a bag of points; they're a tree. One wrist at the
root, then five chains fanning out. Switch to this stage and the bones appear,
connecting wrist → metacarpal → proximal → intermediate → distal → tip down each
finger. The thumb is the odd one — it has no intermediate phalanx, so its chain is one
joint shorter, padded by its metacarpal. This skeleton is the literal
XRHand joint order, and knowing it is what lets you bend a finger, measure
an angle, or attach a ring to exactly the right knuckle.
Stage 3 — Joint radii
Here's something MediaPipe never gave you. Each joint pose carries a
radius — the device's estimate of how thick the hand is at that joint, in
meters. We size every sphere by it: the wrist and metacarpals are fat, the fingertips
taper to little beads. Suddenly it reads as a hand, not a constellation. That
radius is also how you do believable collisions in VR — a fingertip is a ~8 mm
sphere, so "did I touch the button" becomes a sphere test, not a guess.
Stage 4 — Pinch in 3D
The pinch we've measured all series, now in real space. We take the
thumb-tip and index-finger-tip joint positions and compute
their Euclidean distance in meters. When it drops under a threshold the two
tips light up and a line snaps between them. Because this is a 3D distance, it doesn't
lie when your hand tilts toward or away from the viewer — the classic failure of a 2D
pinch, where depth foreshortening makes a wide-open hand look pinched. Watch the readout
in the badge swing as the synthetic hand cycles its pinch.
Stage 5 — The XRHand API
This stage overlays the real joint names on the synthetic hand — the exact
strings you pass to hand.get(...). There are 25 of them and they're
spelled precisely ('index-finger-phalanx-proximal', not
'index_pip'). In a live session you'd loop these names, call
frame.getJointPose(hand.get(name), referenceSpace), and read
pose.transform.position and pose.radius back. We print the
code for that loop below; the overlay here is just so you can see what each label maps
to on a real hand.
Stage 6 — Enter VR
The payoff and the discipline. If this browser reports an immersive-VR device, the
Enter VR button is enabled; press it and Three.js requests a session with
'hand-tracking' as an optional feature, and your real hands replace the
synthetic one. If there's no headset — which is almost certainly the case right now —
the button is disabled, the status line says so, and the synthetic hand keeps running
untouched. The demo never blocks waiting for hardware it can't find. That single rule,
enforced by one await isSessionSupported(...) check, is what separates a
WebXR page that degrades gracefully from one that shows a blank screen to 99% of
visitors.
How the code works
Four pieces carry this episode: the synthetic 25-joint hand that keeps the demo
alive, the Three.js skeleton that draws it, the real XRHand read loop you'd
run on-device, and the gate that decides between them.
(a) The 25-joint synthetic 3D hand
We extend the 21-landmark generator from Episode 02 into true 3D and add the four
joints WebXR has that MediaPipe doesn't: a real thumb metacarpal plus a
metacarpal for index, middle, ring, and pinky (MediaPipe folds those
into the MCP knuckle). The output is an array of 25 { pos: Vector3, radius }
in meters, wrist-relative — the same fields a real getJointPose gives you,
so everything downstream is identical for synthetic and live hands:
// 25 XRHand joints, in canonical order. wrist is the root.
const JOINTS = [
'wrist',
'thumb-metacarpal', 'thumb-phalanx-proximal', 'thumb-phalanx-distal', 'thumb-tip',
'index-finger-metacarpal', 'index-finger-phalanx-proximal', 'index-finger-phalanx-intermediate', 'index-finger-phalanx-distal', 'index-finger-tip',
'middle-finger-metacarpal', 'middle-finger-phalanx-proximal', 'middle-finger-phalanx-intermediate', 'middle-finger-phalanx-distal', 'middle-finger-tip',
'ring-finger-metacarpal', 'ring-finger-phalanx-proximal', 'ring-finger-phalanx-intermediate', 'ring-finger-phalanx-distal', 'ring-finger-tip',
'pinky-finger-metacarpal', 'pinky-finger-phalanx-proximal', 'pinky-finger-phalanx-intermediate', 'pinky-finger-phalanx-distal', 'pinky-finger-tip',
];
// Emit a synthetic hand as 25 {pos, radius}, in METERS, like a real XRHand. t = seconds.
function syntheticHand3D(t, opts = {}) {
const curl = opts.curl ?? (0.18 + 0.16 * Math.sin(t * 1.3)); // breathing curl
const pinch = opts.pinch ?? (0.5 + 0.5 * Math.sin(t * 0.9)); // cycles open↔pinched
const joints = [];
const push = (p, r) => joints.push({ pos: p, radius: r });
// finger fan: root angle, length, base radius. thumb is special-cased below.
const fans = [
{ root: -0.95, len: 0.052, segs: 3, r: 0.011 }, // thumb (metacarpal+2 phalanx+tip)
{ root: -0.30, len: 0.044, segs: 4, r: 0.010 }, // index
{ root: -0.03, len: 0.046, segs: 4, r: 0.010 }, // middle
{ root: 0.24, len: 0.042, segs: 4, r: 0.009 }, // ring
{ root: 0.52, len: 0.034, segs: 4, r: 0.008 }, // pinky
];
push(new THREE.Vector3(0, 0, 0), 0.028); // wrist (fat root)
for (let f = 0; f < 5; f++) {
const { root, len, segs, r } = fans[f];
let c = curl;
if (f === 0) c = Math.max(curl, pinch * 0.75); // thumb folds in on pinch
if (f === 1) c = Math.max(curl, pinch * 0.85); // index folds in on pinch
const a0 = root * (opts.spread ?? 1);
// metacarpal start: spread out from wrist across the palm
let px = Math.sin(a0) * 0.034, py = Math.cos(a0) * 0.042, pz = 0;
let ang = a0;
for (let j = 0; j < segs; j++) {
if (j > 1) ang += c * 0.85; // phalanges bend, palm stays flat
px += Math.sin(ang) * len;
py += Math.cos(ang) * len;
pz += -Math.sin(c) * len * 0.35; // curl pushes the tip toward the palm (−z)
const taper = r * (1 - j * 0.16); // joints get thinner toward the tip
push(new THREE.Vector3(px, py, pz), taper);
}
}
return joints; // length 25, indices line up with JOINTS[]
}
That's the heart of "alive on first paint": no camera, no headset, no network — just a
function of t that produces the exact shape the real API produces.
(b) Drawing the joint skeleton in Three.js
Twenty-five instanced spheres for the joints (so we can recolor and resize them per
frame for free) and a single LineSegments for the bones. We define the bone
pairs once, by joint name, then resolve them to indices — exactly how you'd
draw a real hand:
// Bones: wrist → each metacarpal, then each finger chain. By name, then → indices.
const idx = (n) => JOINTS.indexOf(n);
const CHAINS = [
['wrist', 'thumb-metacarpal', 'thumb-phalanx-proximal', 'thumb-phalanx-distal', 'thumb-tip'],
['wrist', 'index-finger-metacarpal', 'index-finger-phalanx-proximal', 'index-finger-phalanx-intermediate', 'index-finger-phalanx-distal', 'index-finger-tip'],
// …middle, ring, pinky the same…
];
const bonePairs = [];
for (const chain of CHAINS)
for (let i = 0; i < chain.length - 1; i++)
bonePairs.push([idx(chain[i]), idx(chain[i + 1])]);
const jointMesh = new THREE.InstancedMesh(
new THREE.SphereGeometry(1, 16, 12), // unit sphere, scaled per-instance by radius
new THREE.MeshStandardMaterial({ color: 0x38bdf8, roughness: 0.5 }),
JOINTS.length);
scene.add(jointMesh);
const boneGeo = new THREE.BufferGeometry();
boneGeo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(bonePairs.length * 6), 3));
const bones = new THREE.LineSegments(boneGeo, new THREE.LineBasicMaterial({ color: 0x64748b }));
scene.add(bones);
// Per frame: place each instanced sphere, scale it by the joint's radius.
const m = new THREE.Matrix4(), showRadius = stage >= 2;
joints.forEach((jt, i) => {
const s = showRadius ? jt.radius : 0.009; // stage 3+ sizes by radius; earlier = uniform
m.makeScale(s, s, s); m.setPosition(jt.pos);
jointMesh.setMatrixAt(i, m);
});
jointMesh.instanceMatrix.needsUpdate = true;
(c) The real XRHand read loop
This is what runs inside an immersive session, once per frame. You get the
session's input sources, find the one with a .hand, then for each joint
name pull a pose with getJointPose against your reference space. Every pose
is a full 3D transform plus a radius. Guard everything — joints can be null
for a frame when tracking drops:
// Called every frame with the XRFrame; refSpace from session.requestReferenceSpace('local').
function readHands(frame, refSpace) {
for (const source of frame.session.inputSources) {
const hand = source.hand; // an XRHand, or undefined for a controller
if (!hand) continue;
for (const name of JOINTS) { // the same 25 names as the synthetic hand
const jointSpace = hand.get(name); // an XRJointSpace
if (!jointSpace) continue;
const pose = frame.getJointPose(jointSpace, refSpace);
if (!pose) continue; // null when this joint isn't tracked this frame
const p = pose.transform.position; // {x,y,z} in METERS, room space
const r = pose.radius; // joint thickness in meters
placeJoint(name, p.x, p.y, p.z, r);
}
// pinch = 3D distance between the two fingertips, in meters
const tip = (n) => frame.getJointPose(hand.get(n), refSpace)?.transform.position;
const a = tip('thumb-tip'), b = tip('index-finger-tip');
if (a && b) {
const d = Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z);
const pinching = d < 0.025; // ~2.5 cm — tune with hysteresis (Ep23)
}
}
}
(d) Gating Enter-VR + the graceful fallback
The rule from §10 of the brief: never block on a headset. Probe
support with navigator.xr?.isSessionSupported('immersive-vr') — which is
false (or navigator.xr is missing entirely) in a normal or
headless browser — and only enable the button when it's truly supported. Wrap the
probe and the launch in try/catch so a hostile environment can
never throw past you:
// Gate the button. Default state is disabled; synthetic hand is already running.
async function gateEnterVR() {
try {
const ok = await navigator.xr?.isSessionSupported('immersive-vr');
if (ok) {
xrBtn.disabled = false;
setXrStatus('headset detected · press Enter VR');
} else {
xrBtn.disabled = true;
setXrStatus('no immersive-VR device — synthetic hand active');
}
} catch (err) {
xrBtn.disabled = true; // any failure → stay synthetic
setXrStatus('WebXR unavailable (' + err.name + ') — synthetic hand active');
}
}
async function enterVR() {
try {
const session = await navigator.xr.requestSession('immersive-vr', {
optionalFeatures: ['hand-tracking', 'local-floor'],
});
renderer.xr.enabled = true;
await renderer.xr.setSession(session); // Three.js drives the session
refSpace = await session.requestReferenceSpace('local');
usingXR = true; // loop now reads real hands; synthetic hidden
session.addEventListener('end', () => { usingXR = false; }); // back to synthetic on exit
} catch (err) {
setXrStatus('could not start session (' + err.name + ') — staying synthetic');
}
}
gateEnterVR(); // runs once at startup; never throws
Note the importmap is Three.js r170, the same pinned version the gaussian-splatting and three.js series use. We never top-level import anything WebXR; the gate is a feature-detect, and the whole demo reaches a fully working synthetic state with zero network calls beyond loading Three itself.
2.5D vs true 3D — what actually changed
| MediaPipe (Eps 01–17) | WebXR XRHand (today) | |
|---|---|---|
| Joints / hand | 21 | 25 |
| Coordinates | x,y normalized image; z a hint | full 3D transform in meters |
| Per-joint thickness | — | radius in meters |
| Orientation | — | per-joint quaternion |
| Depth / occlusion | approximate | true |
| Hardware | any webcam | headset + HTTPS |
The four extra joints are the metacarpals: the long bones inside the
palm. MediaPipe's index map starts each finger at its MCP knuckle (indices 5, 9, 13,
17) and gives the thumb a CMC at index 1; WebXR instead names a full
*-finger-metacarpal for all four fingers plus a thumb-metacarpal,
and roots them all at the wrist. Same hand, four more named bones, and a
real coordinate frame around it.
Common pitfalls
- WebXR needs a headset and HTTPS — don't assume either. On a phone
or laptop,
navigator.xrmay beundefinedorisSessionSupportedresolvesfalse; overfile://or plain HTTP it won't run at all. Always gate the button on the async support check and keep the synthetic fallback alive. Never wire Enter VR straight torequestSession. - It's 25 joints, not 21. Porting MediaPipe code 1:1 silently drops
the five metacarpals (
thumb-metacarpal,index/middle/ring/pinky-finger-metacarpal). Iterate the fullXRHandjoint set, not a 21-entry array. - Joint poses are full 3D transforms. Each pose has a
position and an orientation (quaternion), in meters. If you only read
positionyou throw away rotation — which is what you need to orient a ring or a fingernail decal. And the units are meters, not normalized [0,1]; don't reuse your(1 - x) * widthmapping. - Poses can be
nullfor a frame. When tracking briefly drops,getJointPosereturnsnullper joint. Guard every call (as in the loop above) or you'll crash on a flicker — the XR equivalent of the empty-landmarks guard from Episode 01. - Always keep the synthetic hand alive. Even on a real headset, hands leave the tracking volume. Treat the synthetic hand as your "no data" state so the scene never goes empty, and so the page is demo-able by anyone without hardware.
Exercises
- Render both hands. Call
syntheticHand3Dtwice with offset positions and opposite phases, draw two skeletons, and on the camera/XR path iterate all input sources with a.hand(left and right). Color them differently. This is the two-hands pattern from Episode 17, now in XR. - Pinch-to-draw in 3D. When the thumb-tip↔index-tip distance drops
under your threshold, start appending the midpoint of the two tips to a
BufferGeometryline every frame; stop when the pinch releases. You'll be painting ribbons in midair — add hysteresis (Episode 23) so the line doesn't stutter at the threshold. - A debug overlay of joint names. Extend Stage 5: render each of the 25 joint names as a small sprite label anchored to its joint, billboarded to face the camera. It's the fastest way to learn the joint vocabulary — and an invaluable tool the first time a real hand looks wrong on-device.
What's next
Episode 19 — Train Your Own Gesture, in the Browser. We've been defining gestures by hand (a pinch is a distance threshold; a fist is a curl sum). Next we flip it: record a few examples of any pose you like — a thumbs-up, a peace sign, a custom spell — and train a tiny classifier live in the page that learns to recognize it from the landmarks, no server, no dataset download. The synthetic hand becomes your training partner.