Interactive Vision From Zero · Episode 07
Paint With Light
Paint With Light is Episode 07 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 .
Hold up a finger and draw a glowing figure-8 in the air. A ribbon of light streams off your fingertip, blooms where you move slow, sprays sparks where you flick fast, and melts from white-hot at the tip to a deep blue as it fades. It's long-exposure light-painting — the trick photographers do with a sparkler and a 10-second shutter — except the sparkler is your hand and the shutter is a particle system running at 60fps in your browser. The clip is hypnotic, and the demo below is already painting one by itself, no camera required.
The whole effect is one idea executed carefully: a pre-allocated pool of GPU particles that we emit at the index fingertip, push in the direction the hand is moving, and fade out over a short lifetime — drawn with additive blending so overlapping particles sum into light. The catch that makes or breaks it is performance: you must never allocate per frame. We build the pool once, then recycle slots in a ring buffer forever. Step through the six stages to watch a single trailing dot grow into a full light-painting brush, then point your own camera at it and sign your name in the dark.
What you're looking at
A dark canvas and a moving point of light at the index fingertip — landmark 8. On autoplay the synthetic hand traces a slow Lissajous figure (a leaning figure-8), so the brush paints a glowing ribbon entirely on its own; that's the screenshot. The bright streak is thousands of tiny particles, each one emitted at the fingertip, nudged in the hand's direction of travel, and faded out over a second or two. Because we draw them with additive blending, places where the strokes overlap glow brighter — exactly like light accumulating on a long-exposure photo.
Mirror, stated up front: this is a selfie view, so we flip the X axis
once when we map the fingertip into the scene — screenX ∝ (1 − landmark.x).
Move your hand right, the brush goes right. The synthetic hand is mirrored the same way,
so synthetic and camera modes feel identical. Forgetting that single flip is the
number-one reason a hand demo feels "backwards," so we name it loudly and apply it in
exactly one place. And the privacy basics: when you opt into the camera, MediaPipe runs
on your device — the video never leaves your machine.
Stage 1 — Trailing dot
The simplest possible brush: one glowing sprite parked at the fingertip, no history at
all. This is the "is my mapping right?" stage. If the dot tracks your fingertip cleanly —
moving right when your hand moves right, living in the middle of the canvas and not stuck
in a corner — every later stage will work. The classic failure here is the dot pinned to
the top-left: that's normalized [0,1] coordinates left unscaled to the
scene's world units. Get the dot following nicely and the painting is just a matter of
leaving a trail behind it.
Stage 2 — Fading trail
Keep a short history of recent fingertip positions and draw them with falloff — newest brightest, oldest dimmest. Suddenly the dot has a comet tail. This is the cheapest possible "trail," and it teaches the core mechanic of light-painting without any real particle system yet: a stroke is just the recent past, drawn faintly. The history is a small fixed-length ring of points, not a growing array — the same no-allocation discipline we lean on hard in the next stage.
Stage 3 — Spray particles
Now the real engine. Instead of redrawing a position history, we emit
particles: every frame, spawn a few new ones at the fingertip from a pre-allocated
pool, give each a tiny random jitter velocity and a lifetime, then integrate and
fade them independently. Crucially, the pool is built once at startup; emitting
just overwrites the oldest slot via a ring-buffer index. Drag emission rate
and lifetime and feel the brush get denser and longer-lived. This is where a
naïve implementation tanks to 12fps — and where doing it right stays glued to 60.
Stage 4 — Velocity spray
The particles were drifting randomly; now they inherit the hand's motion. We track a smoothed fingertip velocity and hand it to every particle we emit, plus a little jitter. Move slowly and particles pool at the tip like dripping paint; flick fast and they spray out in a fan trailing your gesture. This velocity inheritance is the single thing that makes the brush feel physical — the spray is a direct readout of how hard you moved. (Watch the units: that velocity comes from normalized coordinates and must be scaled to world units, or the spray is invisibly tiny or violently huge.)
Stage 5 — Additive glow + color-over-life
The gorgeous look. Two changes: switch the blend mode to additive so overlapping particles sum toward white-hot, and shift each particle's color over its lifetime — born bright and near-white at the tip, aging through your brush hue, dying in a deep ember. Combined with a soft round sprite (we discard the corners and feather the edge in the fragment shader), the stroke stops looking like dots and starts looking like light. Pick a brush color and paint; this is the frame you record.
Stage 6 — Ribbon brush
A different brush entirely. Instead of spraying discrete sparks, we connect the recent
fingertip positions into a smooth, continuous light-ribbon — a glowing
tube of triangles that flows behind your hand, its color cycling along its length. Spark
mode is fireworks; ribbon mode is calligraphy. Switch the brush mode control
between them at any stage to compare. The ribbon is the same recent-history idea from
Stage 2, but turned into solid additive geometry instead of points — the best brush for
signing your name in the air.
How the code works
Four pieces carry the whole episode. In the demo they're wired into one
onLandmarks(hand, dt) function that both the synthetic loop and the real
camera feed call — a single source of truth, so your real hand drops into the exact same
code path the synthetic one uses.
(a) The pre-allocated particle pool (no per-frame allocation)
This is the performance heart of the episode. We allocate every buffer once,
sized for the maximum number of particles we'll ever show, and wrap a single
THREE.Points around them. Emitting a particle never creates an object — it
overwrites the oldest slot, tracked by a wrapping head index (a ring buffer).
The golden rule: nothing inside the render loop calls new.
const MAX = 4000; // hard cap — the pool never grows past this
const pos = new Float32Array(MAX * 3); // xyz per particle
const vel = new Float32Array(MAX * 3); // velocity per particle (world units/s)
const born = new Float32Array(MAX); // spawn time (s)
const ttl = new Float32Array(MAX); // lifetime (s); 0 = dead/free slot
const seed = new Float32Array(MAX); // per-particle random, for hue jitter
const geo = new THREE.BufferGeometry();
geo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
geo.setAttribute('aVel', new THREE.BufferAttribute(vel, 3));
geo.setAttribute('aBorn', new THREE.BufferAttribute(born, 1));
geo.setAttribute('aTtl', new THREE.BufferAttribute(ttl, 1));
geo.setAttribute('aSeed', new THREE.BufferAttribute(seed, 1));
const points = new THREE.Points(geo, particleMaterial);
points.frustumCulled = false; // particles roam; don't let culling blink them
let head = 0; // ring-buffer write cursor — wraps at MAX
(b) Emit at the fingertip, with velocity = smoothed hand delta
Each frame we spawn rate × dt particles. To emit, we write into slot
head, then advance and wrap it — recycling the oldest particle once
the ring fills. The velocity we stamp in is the smoothed hand velocity (computed in part c)
plus a little random jitter so the spray has width. Because we only touch the slots we
wrote, we flag the buffers needsUpdate and let the GPU do the rest:
function emit(p, hv, now, life, jitter) { // p = world fingertip, hv = hand velocity
const i = head; // claim the current ring slot…
head = (head + 1) % MAX; // …and advance, wrapping → recycles oldest
pos[i*3+0] = p.x; pos[i*3+1] = p.y; pos[i*3+2] = p.z;
vel[i*3+0] = hv.x + (Math.random()-0.5) * jitter; // inherit motion + spread
vel[i*3+1] = hv.y + (Math.random()-0.5) * jitter;
vel[i*3+2] = hv.z + (Math.random()-0.5) * jitter;
born[i] = now; ttl[i] = life; seed[i] = Math.random();
}
// in the loop: fractional emission carries over so low rates still emit smoothly
emitAcc += rate * dt;
while (emitAcc >= 1) { emit(tip, handVel, t, lifetime, jitter); emitAcc -= 1; }
geo.attributes.position.needsUpdate = true; // upload only what changed
geo.attributes.aVel.needsUpdate = geo.attributes.aBorn.needsUpdate =
geo.attributes.aTtl.needsUpdate = geo.attributes.aSeed.needsUpdate = true;
(c) The additive ShaderMaterial: soft round sprite + color-over-life
One uniform — the current time — does all the animation on the GPU. The vertex shader
computes each particle's age, scales gl_PointSize by depth (so far sparks
shrink) and shrinks it as the particle dies; the fragment shader carves the square sprite
into a soft disc (discard the corners, feather the edge) and ramps the color from
near-white at birth through the brush hue to a dim ember at death. blending:
AdditiveBlending with depthWrite: false is what produces the glow:
const particleMaterial = new THREE.ShaderMaterial({
uniforms: { uNow:{value:0}, uSize:{value:16}, uDpr:{value:1}, uColor:{value:new THREE.Color('#38bdf8')} },
transparent: true,
depthWrite: false, // additive sprites must NOT write depth…
blending: THREE.AdditiveBlending, // …and sum together into light
vertexShader: /* glsl */`
uniform float uNow, uSize, uDpr;
attribute vec3 aVel; attribute float aBorn, aTtl, aSeed;
varying float vLife; varying float vSeed;
void main() {
float age = uNow - aBorn;
vLife = clamp(age / max(aTtl, 0.0001), 0.0, 1.0); // 0 = newborn, 1 = dead
vSeed = aSeed;
vec3 p = position + aVel * age; // integrate on the GPU
vec4 mv = modelViewMatrix * vec4(p, 1.0);
float grow = (aTtl > 0.0 ? 1.0 : 0.0); // dead slots collapse to 0px
gl_PointSize = uSize * uDpr * grow * (1.0 - 0.55*vLife) * (300.0 / -mv.z);
gl_Position = projectionMatrix * mv;
}`,
fragmentShader: /* glsl */`
uniform vec3 uColor;
varying float vLife; varying float vSeed;
void main() {
float d = length(gl_PointCoord - 0.5);
if (d > 0.5) discard; // square → disc
float a = smoothstep(0.5, 0.0, d) * (1.0 - vLife); // soft edge + fade out
vec3 hot = mix(vec3(1.0), uColor, 0.35); // near-white at birth…
vec3 col = mix(hot, uColor * 0.35, vLife); // …→ brush hue → ember
gl_FragColor = vec4(col, a);
}`,
});
(d) Integrate + fade (and why we don't full-clear the canvas)
Because the shader integrates from each particle's stored velocity and birth time, the per-frame CPU "update" is almost nothing — bump the time uniform and the GPU moves and fades every live particle. The one subtlety is the canvas: if you fully clear it every frame, only the particles still alive show, and short-lived ones leave no streak. To bake a longer light-painting trail we draw a dim translucent quad over the previous frame instead of clearing — old light lingers and decays, exactly like film:
// trivially cheap update: the GPU does the motion. CPU just advances the clock.
particleMaterial.uniforms.uNow.value = t;
// persistence: fade the prior frame instead of wiping it, so trails accumulate.
if (persist) {
renderer.autoClear = false;
renderer.render(fadeScene, fadeCam); // a dim full-screen quad (alpha ~0.12)
renderer.render(scene, camera);
} else {
renderer.autoClear = true; // stages 1–2: clean redraw, no accumulation
renderer.render(scene, camera);
}
Common pitfalls
- Per-frame allocation tanks fps. Calling
new THREE.Vector3()or pushing onto a growing array inside the loop spews garbage and stutters. Pre-allocate a fixed pool and recycle slots with a ring-bufferheadindex. Nothing in the hot path should callnew. - Additive blow-out to white. Additive blending sums color, so a
dense brush quickly clips to a flat white blob. Cap the emission rate, keep per-particle
alpha modest, and let the color-over-life fade pull energy back out. If it's nuking,
lower
emission rateor particle size before anything else. - Velocity from normalized coords is the wrong scale. Landmark deltas
live in
[0,1]image space; multiply by the scene's world span before using them as particle velocity, or the spray is invisibly tiny (or rockets off-screen). State the conversion once and reuse it. - Full-clearing kills trails. Clearing the canvas every frame erases everything but the currently-live particles. For a long-exposure look, fade the prior frame (a dim quad) instead of wiping — or extend particle lifetimes so the trail lives in the pool itself.
- Forgot
depthWrite:false+transparent:true. Additive sprites that write depth occlude each other and the glow turns into hard punched-out holes. Transparent, no depth-write, additive blend — all three together. - Mirror. Skip the
1 − xflip and the brush paints the wrong way. Apply it once, in the fingertip→world mapping, to both synthetic and camera input.
Exercises
- Add forces. Give particles gravity (a constant pull on
aVel.y) so sparks arc and fall, or wire in cheap curl noise so the stroke swirls like smoke. Since the shader integratesposition + aVel*age, the cleanest way is to add an acceleration term:p += 0.5*g*age*age. - Emit from all five fingertips. Loop the emitter over landmarks
4, 8, 12, 16, 20instead of just8, each with its own smoothed velocity. Now you finger-paint with a whole glowing hand at once. - Freeze-frame export. Add a "save" button that grabs the current
painting as a PNG with
renderer.domElement.toDataURL('image/png')and triggers a download. (Create the renderer withpreserveDrawingBuffer: trueso the buffer is still readable at save time.) Instant shareable art.
What's next
Episode 08 — Air Instrument (Season Finale). We bring it all together: two hands, spatial trigger zones floating in space, hit detection when a fingertip's velocity punches through a plane, and a synthesized burst of sound (Web Audio) plus a visual flash on every hit. You'll build a playable air drum kit / harp and literally make music by punching the air — the capstone of everything Season 1 taught about turning a hand into an instrument.