Interactive Vision From Zero · Episode 14

Body Particle Silhouette

Body Particle Silhouette is Episode 14 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 14 · Interactive Vision From Zero · Season 2

Stand in front of the camera and dissolve into ten thousand sparks of light that still, unmistakably, look like you. Lift an arm and the cloud streams after it. Throw a punch and it shatters outward, then gathers itself back into your shape. This is the effect every music video and AR filter reaches for — a glowing particle silhouette that breathes with the person inside it — and it runs at 120 fps in a single HTML file, no GPU compute, no segmentation network, no per-frame allocation.

The trick is that we never actually cut your outline out of the video. We let the 33-point pose skeleton stand in for your body: scatter particles along the bones and across the torso, pull each one home to its assigned spot, and the negative space between the limbs reads as a silhouette for free. The demo below is dancing the synthetic walk on first paint — no camera needed. Step through the six stages to watch a bare skeleton become a living cloud of light, then press use my camera and it becomes your cloud.

0 fps
move your mouse to puppet the body
🔒 runs on-device · nothing leaves your machine
synthetic pose · 9000 particles
High count, additive glow, color-over-life. This is the headline look — become a cloud that takes your shape.

What you're looking at

Every frame, one function — onLandmarks(pose) — receives 33 body points, each an {x, y, z, visibility} in normalized [0,1] image space (x→right, y→down). On first paint those points come from syntheticPose(t), a procedurally walking figure. Press the camera button and they come from MediaPipe's PoseLandmarker instead — same 33 numbers, same downstream code. The particle system never knows or cares which one is driving it.

The view is mirrored like a selfie: we map screenX = (1 - x) * width so moving your body right moves the cloud right. We apply that exact flip to the synthetic figure too, so the autoplay and the camera feel identical. Mirrored axes are the number-one source of "why is it backwards" confusion, so we state it up front and do it in exactly one place.

Stage 1 — The skeleton

The reference. We draw the 33 landmarks as dots and connect them with POSE_CONNECTIONS — torso quad, arms, legs, a stub of neck. This is the raw material the whole episode is built on: there is no image of your body here, just sixteen line segments and a scatter of joints. Convince yourself that this skeleton alone carries enough of your shape to fake a silhouette, and the rest of the episode is just making it beautiful.

Stage 2 — Particles on the joints

Drop a soft additive glow at each of the 33 landmarks. Already it feels more alive than the wireframe — light pools at the shoulders, elbows, wrists, hips, knees, ankles. But it's hollow: 33 bright points floating in the dark, with nothing between them. A constellation, not a body. We need to fill the space along the bones.

Stage 3 — Particles fill the body

This is the key idea of the episode. Instead of one particle per joint, we generate a list of body sample points: walk along every bone and drop points by lerp-ing between its two endpoints, then scatter points across the torso quad (shoulders + hips) with bilinear interpolation. Suddenly the figure is filled — arms are tubes of light, the chest is a slab — and it reads as a silhouette even though we never touched a single video pixel. Low-visibility joints are skipped so a hidden hand doesn't spray particles into the void.

Stage 4 — Drift & return

A frozen fill looks like a diagram. Life comes from motion that resolves. Each particle gets a permanent home — its assigned body sample point — but every frame it also wanders a little (a slow per-particle noise) and is gently pulled back toward home with a spring. The result is a shimmering, breathing cloud that always relaxes back into your shape. Turn the spring off and the cloud evaporates; that tension between drift and return is the entire feel.

Stage 5 — Burst on movement

Now make it react. We track each joint's smoothed velocity between frames. When a joint moves fast — a wave, a kick, a punch — every particle near it gets flung outward along the motion. The cloud explodes into sparks... and then the same spring from Stage 4 reels it all back in. Crank the burst slider and flail: the figure detonates and re-forms, detonates and re-forms. Movement literally throws light off your body.

Stage 6 — Full glowing silhouette

Everything at once, turned up. High particle count, additive blending so overlaps bloom, color that shifts over each particle's life (bright and hot at the core of its home, cooler as it drifts out), and a palette you can swap. This is the headliner: a living cloud of light in your exact shape that dances on its own and shatters when you move. Pick Spectrum and wave.

How the code works

Four ideas carry the whole demo: sample the body into points, pre-allocate a particle pool, integrate attract + drift, and burst from velocity, then draw additively — all with zero allocation inside the render loop.

1 · Sampling body points along the bones and torso

Given the 33 landmarks, we build a flat list of target points. We lerp a handful of points along every bone, then fill the torso quad. We skip any bone whose joints aren't confidently visible so missing limbs don't smear:

// POSE_CONNECTIONS: the 16 bones we walk along (torso, arms, legs, feet, neck)
const POSE_CONNECTIONS = [
  [11,12],[11,23],[12,24],[23,24],   // torso
  [11,13],[13,15],[12,14],[14,16],   // arms
  [23,25],[25,27],[24,26],[26,28],   // legs
  [27,29],[27,31],[28,30],[28,32],   // feet
  [0,11],[0,12],                             // neck-ish
];

// Fill `targets` (a reused Float32Array of x,y pairs) with body sample points.
// Returns how many we actually wrote. Mirror happens here, ONCE: sx = (1 - x).
function sampleBody(pose, W, H, targets) {
  let n = 0;
  const push = (x, y) => { if (n*2+1 < targets.length) { targets[n*2] = x; targets[n*2+1] = y; n++; } };
  const vis = (i) => (pose[i].visibility ?? 1) > 0.4;        // skip low-confidence joints
  const sx = (i) => (1 - pose[i].x) * W, sy = (i) => pose[i].y * H;  // MIRROR X here

  // (a) points strung along every visible bone
  for (const [a, b] of POSE_CONNECTIONS) {
    if (!vis(a) || !vis(b)) continue;
    const steps = 7;
    for (let s = 0; s < steps; s++) {
      const u = s / (steps - 1);
      push(sx(a) + (sx(b)-sx(a))*u, sy(a) + (sy(b)-sy(a))*u);  // lerp along bone
    }
  }
  // (b) fill the torso quad (shoulders 11/12, hips 24/23) by bilinear interpolation
  if (vis(11) && vis(12) && vis(23) && vis(24)) {
    for (let gy = 0; gy < 5; gy++) for (let gx = 0; gx < 4; gx++) {
      const u = gx/3, v = gy/4;
      const topX = sx(12) + (sx(11)-sx(12))*u, topY = sy(12) + (sy(11)-sy(12))*u;
      const botX = sx(24) + (sx(23)-sx(24))*u, botY = sy(24) + (sy(23)-sy(24))*u;
      push(topX + (botX-topX)*v, topY + (botY-topY)*v);
    }
  }
  return n;   // ~ 110+ sample points; particles will be distributed across these
}

2 · The pre-allocated particle pool

The cardinal sin of particle systems is allocating inside the loop. We allocate once, up front, as flat typed arrays, and reuse them forever. Each particle stores a position, a velocity, a life value (for color-over-life), a seed (for unique drift), and an index into the body-target list it calls home:

// One-time allocation. MAX is the slider's ceiling; we just vary how many we DRAW.
const MAX = 14000;
const px = new Float32Array(MAX), py = new Float32Array(MAX);   // position
const vx = new Float32Array(MAX), vy = new Float32Array(MAX);   // velocity
const life = new Float32Array(MAX);                            // 0..1, drives color
const seed = new Float32Array(MAX);                            // per-particle phase
const home = new Int16Array(MAX);                              // which body sample it targets

for (let i = 0; i < MAX; i++) {
  px[i] = Math.random()*W; py[i] = Math.random()*H;   // start scattered
  seed[i] = Math.random()*1000;
  home[i] = i;                                         // reassigned each frame to a real sample
}

3 · Attract to home + drift integration

Each frame we map every drawn particle onto a body sample (round-robin, so the points spread evenly across all the bones), then integrate: a spring pulls it toward home, a slow sine-based drift makes it wander, and damping keeps it from oscillating. Crucially the particle always returns — without the spring, the shape dissolves in a second:

// nTargets = how many body samples sampleBody() wrote this frame; count = slider value
for (let i = 0; i < count; i++) {
  const tIdx = (i % nTargets) * 2;          // round-robin onto a body sample
  const hx = targets[tIdx], hy = targets[tIdx+1];

  // slow per-particle drift (no allocation — just sin of time + seed)
  const dxx = Math.sin(t*0.7 + seed[i]) * driftAmp;
  const dyy = Math.cos(t*0.9 + seed[i]*1.3) * driftAmp;

  // spring toward home (+ drift offset). k = stiffness; bigger = snappier return
  vx[i] += ((hx + dxx) - px[i]) * k;
  vy[i] += ((hy + dyy) - py[i]) * k;

  vx[i] *= damp; vy[i] *= damp;                  // damping = the "honey" feel
  px[i] += vx[i]; py[i] += vy[i];

  // life = how close to home → drives color-over-life (1 at home, 0 when flung out)
  const dist = Math.hypot(px[i]-hx, py[i]-hy);
  life[i] = Math.max(0, 1 - dist / 120);
}

4 · Burst from joint velocity + additive draw

To make movement throw the cloud, we keep the joints' positions from last frame, compute a smoothed velocity, and when a nearby joint is moving fast we add an impulse to the particle. Then we draw — additively, with a capped per-particle alpha so dense overlaps glow instead of blowing out to white. A pre-rendered radial-gradient sprite means each particle is one cheap drawImage, no per-frame gradient creation:

// jvx/jvy: smoothed per-joint velocity (lerped each frame — see pitfalls)
// For each particle, find its home joint's velocity and kick it if fast:
if (speed > burstThreshold) {
  const kick = (speed - burstThreshold) * burstGain;
  vx[i] += jvx[j] * kick + (Math.random()-0.5) * kick * 0.6;
  vy[i] += jvy[j] * kick + (Math.random()-0.5) * kick * 0.6;
}

// --- additive draw, no per-frame allocation ---
ctx.globalCompositeOperation = 'lighter';            // ADDITIVE blending
for (let i = 0; i < count; i++) {
  const c = palette(life[i]);                         // color-over-life lookup
  ctx.globalAlpha = 0.10 + life[i] * 0.35;            // CAP alpha so it can't blow out
  ctx.drawImage(sprite[c], px[i]-R, py[i]-R, 2*R, 2*R); // pre-baked glow sprite
}
ctx.globalCompositeOperation = 'source-over';

Notice what is not here: no new, no array .push(), no createRadialGradient inside the loop. Sixty (or a hundred and twenty) times a second, we only read and write numbers we already own. That discipline is the difference between a buttery 120 fps and a stuttering mess at a few thousand particles.

The camera swap — teaching the real API, lazily

The synthetic figure and the webcam feed the exact same onLandmarks(pose). The MediaPipe import lives inside the button handler, wrapped in try/catch, so a camera-less load never touches the network and never throws. On failure we just keep dancing the synthetic walk:

async function enableCamera() {
  try {
    const { PoseLandmarker, FilesetResolver } =
      await import('https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.18');
    const fileset = await FilesetResolver.forVisionTasks(
      'https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.18/wasm');
    landmarker = await PoseLandmarker.createFromOptions(fileset, {
      baseOptions: { modelAssetPath: POSE_TASK, delegate: 'GPU' },
      runningMode: 'VIDEO', numPoses: 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; the demo never stops
  }
}

Common pitfalls

  • Allocating inside the loop. A new or a fresh {x,y} per particle per frame is thousands of allocations a second — the garbage collector will saw your frame rate in half. Pre-allocate flat typed arrays once and only ever mutate them, as in block 2.
  • Additive blow-out. With 'lighter' blending, dense overlaps sum past 1.0 and the body becomes a featureless white blob. Cap per-particle alpha (here ~0.1–0.45) and/or the particle count, and let the dark gaps do the work of reading as a silhouette.
  • Jittery movement detection. Raw frame-to-frame joint deltas are noisy and will trigger phantom bursts while you stand still. Smooth the per-joint velocity (jvx = lerp(jvx, newVx, 0.3)) and only burst above a threshold.
  • The shape dissolves. Drift without a return force is just an explosion in slow motion. Every particle must be sprung back toward its home sample or the cloud evaporates within a second. Drift and return are a pair; never ship one without the other.
  • Mirror. Selfie view flips X. Do screenX = (1 - x) * width in exactly one place — here, inside sampleBody — and apply it identically to synthetic and camera. Mirror in two places and you've un-mirrored it; mirror in zero and your cloud lunges the wrong way.
  • Low-visibility joints. When a limb leaves frame, MediaPipe still returns a landmark, just with low visibility. Sampling along an invisible bone sprays particles across the screen. Gate every sample on visibility > 0.4.
  • Camera only on localhost/HTTPS. Opening the file as file:// silently blocks getUserMedia. The synthetic figure still runs everywhere; the webcam needs a secure context.

Exercises

  1. Long-exposure trails. Instead of clearing the canvas each frame, paint a translucent black rectangle over it (ctx.fillStyle = 'rgba(0,0,0,0.12)'; fillRect). Particles now leave glowing light-painting trails — flail an arm and watch it streak. Tune the alpha for short tails vs. ghostly long ones.
  2. Color by body region. Right now color comes from each particle's life. Instead, tint by where home is: warm hues for the arms (bones touching 11–16), cool for the legs (23–28), white-hot for the torso. Tag each body sample with a region id in sampleBody and look it up at draw time.
  3. Shatter on a gesture. Detect arms-crossed (wrists 15/16 swap sides of the body center) or a clap (wrists suddenly close together), and on the trigger blast every particle outward at once with a big radial impulse — a full-body shatter that re-forms a beat later. Add hysteresis so it fires once per gesture, not every frame it's true.

What's next

Episode 15 — Multi-Person Tracking. So far it's been one body, one cloud. Next we bump numPoses past one, learn to keep identities stable as people cross and overlap, and give each tracked person their own colored particle silhouette — a whole room turned into dueling clouds of light. The pool discipline you built today is exactly what lets it scale to a crowd.

Hungry for more particles? The Gaussian Splatting From Zero series renders millions of fuzzy blobs on the GPU, and the Shaders From Zero series shows how to move this whole integration step onto the GPU when CPU particles finally run out of headroom.