Interactive Vision From Zero · Episode 17
Two-Hand 3D Manipulation
Two-Hand 3D Manipulation is Episode 17 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 .
Reach out with both hands, pinch the air, and you're holding a cube that isn't there. Spread your hands apart and it grows. Twist them like you're turning a steering wheel and it rotates. Move them together and the cube drifts across the scene, hanging exactly between your fingertips. No mouse, no gizmo, no keyboard shortcut — just two hands doing the thing hands have always done: grabbing an object and moving it through space.
This is the moment the series has been building toward. We've tracked one hand, read pinches, mapped landmarks to a flat canvas. Now we lift everything into 3D and use two hands at once. The trick that makes it feel physical is almost embarrassingly simple: the midpoint between your hands is the object's position, the angle of the line between them is its rotation, and the distance between them is its scale. Capture those three numbers when you grab, apply the deltas while you hold — and a rigid object is now bolted to the space between your palms. The demo below is already doing it with two synthetic hands. Then it's your turn.
What you're looking at
A Three.js scene with one floating object and two glowing hand cursors — a small sphere at each index fingertip, with a connecting bar that lights up when that hand is pinching. The cursors are driven by hand landmarks: right now from two synthetic hands that orbit on gentle Lissajous paths and pinch on their own timers, so the demo is alive the instant the page paints, with no camera and no network call. Hit use my camera and the exact same cursors snap to your real hands.
The whole pipeline is the same one from Season 1, widened to two hands and lifted into 3D:
Step through the six stages with the stage selector. Each one switches
on one more degree of freedom, so you can feel them accumulate into the full "hold it
in space" interaction.
Stage 1 — Two hand cursors
The foundation: two cursors, mapped from landmarks into the 3D scene. Each hand's
index fingertip — landmark 8 — is a normalized (x, y) in
[0,1] image space. We un-project it onto a fixed plane at
a chosen depth so it becomes a real 3D point the camera can see. The object just sits
there idling; nothing is grabbed yet. Watch the two spheres drift — that's two
independent hands, each a full 21-landmark structure, sharing one code path.
Stage 2 — One-hand grab
Now pinch matters. When a hand's thumb and index tips come close enough, that hand grabs: the cursor bar lights up, and the object teleports to follow that fingertip until you release. This is the simplest possible grab — position only, one hand. Release (open the pinch) and the object stays where you dropped it. It's the same pinch detector from Episode 03, distance plus hysteresis, now wired to "carry" instead of "click."
Stage 3 — Two-hand grab
Pinch with both hands and the object snaps to the midpoint between your two fingertips. This already feels different — instead of dragging a thing by one corner, you're cradling it between two points, and it sits calmly in the middle. Move both hands together and it translates; the midpoint is a far steadier anchor than a single jittery fingertip. This is the position channel of the full transform, on its own.
Stage 4 — Two-hand rotate
Keep both hands pinched and rotate them around each other — like turning an invisible wheel. The object spins to match. The angle of the vector from your left hand to your right hand becomes the object's rotation. The key idea: we capture the reference angle at the instant you grab, then apply only the change in angle since then. That way the object doesn't snap to some absolute orientation when you grab — it keeps its current pose and turns relative to it, exactly like a real object would.
Stage 5 — Two-hand scale
Now spread your pinched hands apart and bring them together. The object grows and shrinks. The distance between the two fingertips drives scale, again as a ratio against the distance captured at grab-start: pull your hands twice as far apart as when you grabbed, and the object doubles. We clamp the scale so a fully-closed pinch-pair can't collapse the object to a singularity or blow it up off-screen.
Stage 6 — Full transform
All three at once. Pinch with both hands and the object is rigidly attached to the space between them: slide to translate, twist to rotate, spread to scale — simultaneously, the way you'd actually manipulate a physical thing. This is the payoff. Releasing either pinch drops it, frozen in whatever pose your hands last dictated. The synthetic hands run a little choreography here that does all three, so you can watch the "holding it" feel before you try it yourself.
How the code works
Four pieces carry the whole demo: mapping a landmark into 3D, detecting each hand's
pinch, computing the two-hand transform, and the single onLandmarks path
that both synthetic and camera input flow through.
1 · Normalized landmark → a 3D scene point
A landmark is a 2D point in [0,1] image space. A 3D scene has depth. To
bridge them we pick a fixed z-plane in front of the camera and
un-project the 2D point onto it. We convert the normalized coordinates to
normalized device coordinates (NDC, the [-1,1] cube Three.js
projects into), build a ray through that pixel, and intersect it with our plane. The
mirror flip lives right here, in the X term — selfie view, so moving your hand right
moves the cursor right.
// Fixed plane the hands live on: z = PLANE_Z in world space (in front of camera).
const PLANE_Z = 0;
const _ray = new THREE.Ray();
const _plane = new THREE.Plane(new THREE.Vector3(0, 0, 1), -PLANE_Z);
// lm = {x,y,z} normalized landmark → THREE.Vector3 on the z-plane.
function landmarkToScene(lm, out) {
// mirror X (selfie), map [0,1] → NDC [-1,1]; y flips because image y points down
const ndcX = (1 - lm.x) * 2 - 1;
const ndcY = 1 - lm.y * 2;
// build a ray from the camera through that NDC point, hit the plane
_ray.origin.setFromMatrixPosition(camera.matrixWorld);
_ray.direction.set(ndcX, ndcY, 0.5).unproject(camera).sub(_ray.origin).normalize();
return _ray.intersectPlane(_plane, out) || out.set(ndcX * 2.5, ndcY * 1.6, PLANE_Z);
}
Fixing the plane is a deliberate simplification: a single camera can't recover true
depth from one 2D point, so we declare one. The landmark's own z
is a rough hint, not metric, so we don't trust it for placement (Episode 18 gets real
per-joint depth from WebXR). Everything the hands do happens on this plane.
2 · Per-hand pinch detection (distance + hysteresis)
Straight from Episode 03, now run once per hand. Pinch is the distance between the
thumb tip (4) and index tip (8). A single threshold would flicker maddeningly right at
the boundary, so we use two thresholds: you have to come closer than
ON to start a pinch, and drift past the looser OFF to end it.
The gap between them is the hysteresis that kills the chatter.
// One latch per hand so the two hands don't share pinch state.
const PINCH_ON = 0.05, PINCH_OFF = 0.08; // normalized distance
function updatePinch(hand, latch) {
const a = hand[4], b = hand[8]; // thumb tip, index tip
const d = Math.hypot(a.x - b.x, a.y - b.y);
if (!latch.pinching && d < PINCH_ON) latch.pinching = true; // engage
else if (latch.pinching && d > PINCH_OFF) latch.pinching = false; // release
return latch.pinching;
}
3 · The two-hand transform (capture on grab, apply deltas)
The heart of the episode. When the grab begins (the set of pinching hands changes), we snapshot a reference: the midpoint, the angle, and the distance between the hands right now, plus the object's current position, rotation, and scale. While the grab is held, we compute the same three quantities live and apply the differences — angle delta to rotation, distance ratio to scale, midpoint delta to position. Capturing references is what stops the object from jumping the instant you grab it.
let grab = null; // null when nothing held; else the captured reference
function twoHandTransform(pA, pB, obj) {
const mid = pA.clone().add(pB).multiplyScalar(0.5); // midpoint → position
const ang = Math.atan2(pB.y - pA.y, pB.x - pA.x); // between-hands angle → rot
const dist = pA.distanceTo(pB); // between-hands dist → scale
if (!grab) { // grab just started: snapshot
grab = {
mid: mid.clone(), ang, dist,
pos: obj.position.clone(),
rotZ: obj.rotation.z,
scale: obj.scale.x,
};
return;
}
// apply deltas relative to the captured reference
obj.position.copy(grab.pos).add(mid.clone().sub(grab.mid)); // translate
obj.rotation.z = grab.rotZ + (ang - grab.ang); // rotate
const s = THREE.MathUtils.clamp(grab.scale * (dist / grab.dist), 0.25, 3.5);
obj.scale.setScalar(s); // scale (clamped)
}
Each stage simply masks which lines run: Stage 3 applies only the translate, Stage 4 adds rotation, Stage 5 adds scale, Stage 6 runs all three. The snapshot-and-delta structure is identical throughout — that's what makes the interaction composable.
4 · One onLandmarks(hands) for synthetic and camera
The non-negotiable rule of the series: synthetic input and camera input flow through
the same downstream function. hands is an array of zero, one, or
two hands, each a 21-landmark array — exactly MediaPipe's shape, exactly the synthetic
generator's shape. Nothing below this line knows or cares where the hands came from.
function onLandmarks(hands) {
// resolve up to two hands → scene cursors + pinch latches
const active = [];
for (let i = 0; i < 2; i++) {
const h = hands[i];
cursors[i].visible = !!h;
if (!h) { latches[i].pinching = false; continue; }
landmarkToScene(h[8], cursors[i].position); // index tip → cursor
const pinching = updatePinch(h, latches[i]); // per-hand pinch
active.push({ pos: cursors[i].position, pinching });
}
applyStage(active); // stage logic decides grab / 1-hand / 2-hand transform
}
// the render loop picks the source, then calls the SAME onLandmarks:
function readHands(t) {
if (usingCamera && landmarker && video.readyState >= 2) {
const res = landmarker.detectForVideo(video, performance.now());
return res.landmarks || []; // 0–2 hands from MediaPipe
}
// two synthetic hands: different palms + phase → an array of two
return [syntheticHand(t, leftPos(t), leftOpts(t)),
syntheticHand(t, rightPos(t), rightOpts(t))];
}
And the camera swap stays lazy: MediaPipe is never imported at the
top of the file. It's pulled in by a dynamic import() the first time you
click the button, wrapped in try/catch so a missing webcam or denied
permission just leaves you on the synthetic hands with a friendly status line — never a
crash. Note the one new option versus Season 1: numHands: 2.
async function enableCamera() {
try {
const { HandLandmarker, FilesetResolver } =
await import(/* @vite-ignore */ 'https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.18');
const fileset = await FilesetResolver.forVisionTasks(MP_WASM);
landmarker = await HandLandmarker.createFromOptions(fileset, {
baseOptions: { modelAssetPath: HAND_TASK, delegate: 'GPU' },
runningMode: 'VIDEO', numHands: 2, // ← two hands
});
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
}
}
Common pitfalls
- Trying to recover real depth from one camera. You can't — a 2D
point plus a monocular view is ambiguous. Fix a z-plane and un-project onto it
(above). Don't drive position from the landmark's
z; it's a coarse hint, not metric. Real per-joint depth is an XR feature, which is exactly Episode 18. - The object jumps the instant you grab it. You're applying the absolute midpoint / angle / distance instead of the delta from a grab-start snapshot. Capture the reference (midpoint, angle, distance, and the object's current pose) the moment the grab begins, then apply only the change.
- Rotation feels reversed or off-axis. Be explicit about the
rotation frame. We rotate around screen-facing Z using
atan2(dy, dx)on the two cursor positions. Mix in the mirror flip and a sign error sneaks in fast — twist the synthetic hands first to confirm the direction before blaming the camera. - Scale explodes or collapses. Distance ratios are unbounded: a
nearly-closed pinch-pair divides by a tiny number. Always
clampthe result (we use 0.25×–3.5×), and scale by the ratio to the captured distance, never the raw distance. - Hands go the wrong way. The classic mirror bug — you forgot the
1 - xflip. Apply it to both synthetic and camera landmarks so the two modes behave identically. - Pinch chatters at the threshold. One threshold flickers; use two (hysteresis). And keep a separate latch per hand, or one hand's pinch will stomp the other's state.
- Lost tracking crashes the transform. MediaPipe returns fewer hands when one leaves frame. Guard for missing hands, drop the grab cleanly when both pinches aren't present, and never index into a hand that isn't there.
Exercises
- Snap-to-grid on release. When the grab ends, round the object's position to the nearest grid cell and its Z-rotation to the nearest 45°, easing it there over a few frames. Suddenly placement feels intentional instead of approximate.
- Throw with momentum. Track the midpoint's velocity over the last few frames. On release, keep moving the object along that velocity with a little drag so it coasts to a stop — now you can toss the object across the scene.
- A second object. Add a second mesh and, on grab-start, grab whichever object is nearest the midpoint. With two hands you can only hold one at a time — but choosing which makes the scene feel like a real workspace. (Bonus: one object per hand for true bimanual editing.)
What's next
Episode 18 — WebXR Hand Tracking. We trade the un-projected z-plane
for the real thing: a headset that reports 25 joints per hand with
genuine 3D positions, no plane-fixing required. You'll meet the XRHand API,
learn why it's 25 joints instead of MediaPipe's 21, and keep a synthetic 3D hand as the
alive-on-first-paint baseline so the demo runs without a headset — gated behind
navigator.xr?.isSessionSupported('immersive-vr'). The grab-rotate-scale
instincts you just built carry straight over, now in true volumetric space.