Dee Bee

Air Ink / notes from the build

How Air Ink works.

The AI models that find your hand, the rules that turn 21 points into ink, fire, fog and pictures, and the real code with a note beside each step.

Air Ink's mirror canvas, with glowing cat ears, whiskers, and a hand showing its tracking points

Part 1 · How it works

Air Ink has two halves. Google's AI models answer one question about each camera picture: where are your hands, and what shape are they making? The code written for Air Ink turns those answers into ink, fire, fog and pictures. This happens about 30 times a second, all inside your browser.

InputCamera pictureabout 30 a second, mirrored
Google’s MediaPipe models · used as they are
  1. Palm detectorfinds a box around each palm
  2. Hand landmarksplaces 21 points per hand
  3. Gesture classifiernames one of 7 shapes
Code written for Air Ink
  1. Rules and smoothingpinch, flick, blow, frame, 3-frame wait
  2. Four canvas layersvideo, ink, fog, fire and dots
Only when Fog is on: the microphone’s loudness and a second Google model, the face model (lip shape), also feed the rules.

This page has two parts. Part 1 explains how it works in plain words. Part 2 shows the real code, with a note beside each step.

1. The AI models: what Google built

Air Ink uses two finished AI models from Google's MediaPipe toolkit. Nobody here trained them: the site keeps a copy of each one, and your browser runs it as it is. Each model is a single .task file, which is really a small bundle of several neural networks packed together.

The hand model: gesture_recognizer.task (8.4 MB)

Inside this one file are three networks that run one after another.

  1. Palm detector. It looks at the whole camera picture, shrunk to a small square, and draws a box around each palm. It looks for palms, not whole hands, because a palm is rigid and roughly square, while fingers bend into endless shapes. A rigid object is much easier to find.
  2. Hand landmark model. It looks only inside the palm box, at a sharper crop, and places 21 points on the hand: the wrist, then four points along each finger and the thumb. For each point it gives an x and y (where it is in the picture, from 0 to 1) and a z (rough depth compared with the wrist). It also says how sure it is that a hand is really there, and whether it looks like a left or right hand.
  3. Gesture classifier. It reads the 21 points (not the pixels) and gives a score to each of 7 ready-made shapes: Closed_Fist, Open_Palm, Pointing_Up, Thumb_Down, Thumb_Up, Victory and ILoveYou, plus None. Air Ink uses the first six.

Why it's fast after the first frame: once a hand is found, the 21 points from the last frame predict where the hand is in the next one. So the palm detector rests, and only the landmark model runs. The palm detector wakes up again only when the hand is lost.

How it learned: Google trained the landmark model on about 30,000 real hand photos where people marked the 21 points by hand, plus computer-drawn hands in many poses and kinds of lighting. The numbers are stored as "float16", meaning each weight uses 16 bits instead of 32. That halves the download with almost no loss in accuracy.

The face model: face_landmarker.task (3.8 MB)

This one loads only when you turn on Fog. It also has three parts: a face detector, a face mesh model that places 478 points on the face, and a "blendshape" model. Blendshapes are 52 scores from 0 to 1 that describe the face's expression, such as jawOpen, eyeBlinkLeft or mouthSmileLeft. Air Ink reads only two of them, mouthPucker (lips pushed forward) and mouthFunnel (lips rounded into an O), plus points 13 and 14, the middle of the upper and lower lip, so the fog starts at your mouth.

What the models do not do

The models know nothing about drawing, fire, fog or frames. They only answer "where are the hands, where is each of the 21 points, and which of 7 shapes is it?" Everything else in Air Ink is ordinary code written on top of those answers.

2. The engine: how the models run in a browser tab

The models are only numbers. To run them, Air Ink uses MediaPipe Tasks Vision version 1.1.1, Google's free runtime (Apache 2.0 licence). It has two parts, both stored on deebee.lol:

  • vendor/vision_bundle.mjs (156 KB): the JavaScript that Air Ink's code talks to. It offers GestureRecognizer and FaceLandmarker.
  • vendor/wasm/vision_wasm_internal.wasm (13.5 MB): the heavy engine, written in C++ by Google and compiled to WebAssembly. WebAssembly is a format browsers can run almost as fast as a normal installed program, so nothing has to be installed.

Graphics chip first, then processor. When Air Ink starts a model, it first asks for the GPU delegate. That runs the maths on your graphics chip through WebGL. If that fails, it tries again with CPU. The camera tag on the page shows which one you got, for example GPU 12 MS.

Self-hosted, not borrowed. Most MediaPipe examples load the engine and models from Google's servers. Air Ink keeps its own copies on deebee.lol instead. That way the page keeps working if Google moves a file, the versions never change by surprise, and no request goes to Google while you play. THIRD_PARTY.md lists where each file came from and its fingerprint (sha256). A test checks those fingerprints, so a damaged file is caught before publishing.

How much is downloaded. On your first camera visit: 13.5 MB of engine plus 8.4 MB of hand model, about 21 MB. Fog adds 3.8 MB later. The browser keeps them in its cache for the next visit.

Time budget. At 30 frames a second, each frame has 33 milliseconds for everything. Most of that goes to the hand model. When the camera is on, the "Under the hood" section on the Air Ink page measures and shows the real numbers on your device. On the test computer, which has no real graphics chip, the model took about 230 ms per frame. A normal laptop should be many times faster, but that hasn't been measured yet.

3. How the code is organised

Everything lives in one folder, projects/air-ink/, plus one test file. The code is split so the gesture rules are pure maths, with no screen or camera in them. That lets them be tested automatically on a server.

File What it does Written by
index.html The page: the full-screen mirror, the toolbar, the gesture dock, the start card, and the "Under the hood" text Air Ink
air-ink.css All the styles, including the phone layout Air Ink
air-ink.js The main program: starts the camera, runs the models every frame, draws ink, fog and fire, takes snapshots, runs mouse mode Air Ink
gestures.mjs The rules: which tool a hand means, pinch, L-shape, lighter flick, blowing, smoothing, mapping points onto the screen Air Ink
hand.mjs The drawn stick hand for mouse mode and the little gesture icons, using the same 21-point layout as MediaPipe Air Ink
THIRD_PARTY.md Where every Google file came from, its licence and its fingerprint Air Ink
vendor/… MediaPipe's JavaScript and WebAssembly engine Google
models/… The hand and face models Google
scripts/test-air-ink.mjs 12 automatic tests, also run by GitHub before every publish Air Ink

4. One frame, step by step

The browser calls the function cameraFrame about 60 times a second, each time the screen refreshes. This is what it does each time.

  1. Draw the mirror. The camera picture is drawn onto the bottom layer, flipped left to right like a mirror. It is "cover-fitted": scaled up just enough to fill the whole screen, with the extra edges cut off. The function coverFit works out that scale and the offsets.
  2. Run the hand model, but only on new pictures. A webcam gives about 30 pictures a second, half the screen rate. The code checks video.currentTime, and only when a new picture has arrived does it call recognizeForVideo(video, time). It times each call, which is where the "ms" on the page comes from.
  3. Move the 21 points onto the screen. The model's x and y run from 0 to 1 over the raw, unflipped camera picture. The function toScreen turns them into screen pixels and flips x for the mirror: screen x = width − (offset x + x × drawn width), and screen y = offset y + y × drawn height.
  4. Decide the tool. The function classify looks at all hands. Two hands both making an L means Frame. Otherwise the biggest hand wins, because it is usually the closest one. Then toolFor picks the tool for that hand (see section 5).
  5. Wait for 3 frames in a row. While you change shape, the model's answer flickers for a split second. The Debouncer only switches tool after the same answer comes 3 model frames in a row, about 0.1 s. That's why you don't get stray marks while changing shape.
  6. Pick the point the tool works at. Draw and Lift pen use point 8, the index fingertip. Pinch uses the middle between points 4 and 8. Erase, Clear, Snapshot, Undo and Fire use the centre of the palm (the average of points 0, 5, 9, 13 and 17).
  7. Smooth that point. Even a still hand makes the points shake by a few pixels. A One Euro filter (a well-known method from 2012) smooths the point. It smooths strongly when the hand moves slowly, so lines are steady, and lightly when it moves fast, so the pen doesn't lag. In the code its strength is cutoff = 1.2 + 0.015 × speed.
  8. Do the tool's action (the act function): draw a line, erase, move the drawing, or count up a hold timer.
  9. Update the effects. Fire particles rise, fog spreads or slowly fades, and the top layer redraws the 21 dots, the pen cursor and any hold ring.
  10. Report. The status chip shows what is happening ("Drawing", "Hold to clear…"). The camera tag shows frames per second and model time. Twice a second, the "Under the hood" section is updated with your live numbers.

Four see-through layers

The mirror is four <canvas> sheets stacked on top of each other: video at the bottom, then ink, then fog, then UI (fire, dots and cursors). Keeping them apart is what makes the effects easy:

  • The eraser cuts holes only in the ink sheet (a drawing mode called destination-out), so it never touches the fog.
  • A snapshot just stacks the video, ink and fog sheets into one picture. The dots and cursors are left out.
  • Undo keeps a copy of the ink sheet before each action, up to 15 copies, and puts the last one back.

How a line looks smooth

The pen gets a new point only 30 times a second. Joining those points with straight lines would look jagged. Instead, each new piece is a curve that bends through the last point and ends halfway to the new one (a "quadratic curve through midpoints"). A soft glow in the same colour (shadowBlur) gives the neon look.

5. The gesture rules, one by one

All rules are in gestures.mjs. One idea runs through them: every distance is measured in palm sizes. Palm size is the distance from the wrist (point 0) to the middle-finger knuckle (point 9). A hand close to the camera looks big and a far one looks small, but measured in palm sizes they come out the same. So the rules work at any distance.

Choosing the tool for one hand

The checks in toolFor run in this order, and the first one that matches wins:

  1. Pinch. If the thumb tip (4) and index tip (8) are closer than 0.28 palm sizes, it's a pinch. The only exception is when the model says Closed_Fist, because in a fist those two tips also touch.
  2. MediaPipe's own answer. If the gesture classifier named one of its six shapes, Air Ink uses it: Pointing_Up = Draw, Victory = Lift pen, Open_Palm = Erase, Closed_Fist = Clear, Thumb_Up = Snapshot, Thumb_Down = Undo.
  3. A backup check. If the classifier said None, the code counts straight fingers itself. A finger is straight when its tip is at least 12% further from the wrist than its middle joint. Index only = Draw; index and middle = Lift pen; all four = Erase; none = fist.

Draw, Lift pen, Erase, Pinch

  • Draw adds to the line at the smoothed index fingertip. Over the toolbar, the pen lifts by itself so you can reach the buttons.
  • Lift pen moves a dashed ring with your finger but leaves no mark.
  • Erase cuts a circle about one palm wide out of the ink layer, following the palm's centre.
  • Pinch over a toolbar button presses it once. It won't press again until you let go. Pinch anywhere else picks up the whole drawing and drags it.

Hold gestures: Clear, Snapshot, Undo

These act only after you hold the shape: a fist for 1.5 s, a thumbs up for 1.2 s, a thumbs down for 0.5 s. A ring around your hand fills up as the timer runs. After the action, it locks until you change shape, so holding a fist clears only once.

Fire: the lighter flick

A flick is a movement, not a shape, so no single frame can show it. The FlickDetector keeps the last half second of one number: how far the thumb tip (4) is below the index knuckle (5), in palm sizes. A flick is that number rising by more than 0.3 (the thumb snaps down) and falling back by at least 0.24 (it springs up) within that half second.

  • It only listens while your hand is in a thumbs up, a fist, or an unknown shape. So pointing or waving never sets you on fire.
  • Once lit, the flame stays at your thumb tip until you show an open palm, one or two fingers, a pinch or a frame, or until your hand is gone for 0.6 s.
  • The flame is made of small glowing dots. Each frame adds 4 new ones at the thumb tip. They rise, shrink, and change from pale yellow to orange to red as they fade. The strike adds a burst of 14 sparks that fall with gravity, plus an orange glow over the video.

Fog: blowing

Blowing is hard to see on a camera, so the BlowDetector needs two clues at the same time.

  • Sound. Turning on Fog opens the microphone with echo cancelling, noise suppression and automatic volume all switched off. Those features are made to remove exactly the rushing noise a breath makes. Each frame, the code measures the loudness (the "RMS", a kind of average volume).
  • Lips. Every second frame, the face model gives the mouthPucker and mouthFunnel scores. The higher of the two must be above 0.3.
  • Room noise. The detector slowly learns how loud your room normally is. "Loud" means more than 4 times that, and never less than 0.03.
  • Timing. Both clues must hold for 0.2 s to start fogging. Fogging stops 0.25 s after either clue drops.

While you blow, a soft white cloud grows from your mouth. After you stop, it fades a little every 0.3 s and is gone after 20 s. If you point at fogged glass, your finger wipes the fog instead of drawing, so you can write in the mist. Pressing the 9 key also fogs the glass, for when there is no microphone.

Frame: two L hands

The function isL says a hand is an L when the index and thumb are straight, the middle and ring fingers are folded, and the angle between the index (5→8) and the thumb (2→4) is between 55° and 125°. With two L hands:

  • Each corner of the frame is the inside of the L, halfway between points 2 and 5. Both corners are smoothed.
  • The rectangle stretches between the two corners and must be at least 40 pixels on each side.
  • If the corners move slower than 15% of the screen's short side per second, a timer runs. After 1 second of holding still, the code cuts out just that rectangle from the video, ink and fog layers and puts it in the tray. It then locks until you drop your hands.

6. Mouse mode, loading, privacy and errors

Mouse mode

Mouse mode is the original clickable mockup, kept as a fallback. Instead of a camera, a painted room with a person is drawn on the video layer, with a little film grain. Instead of a real hand, hand.mjs builds a stick hand with the same 21 points. It starts from fixed palm points and bends each finger by angles set for that shape: "point" bends all fingers except the index, "fist" bends them all, and so on. The hand follows your mouse, and the number keys 1 to 0 or the dock buttons change its shape. Because it uses the same 21-point layout, the same drawing code (act) runs in both modes.

Starting the camera

When you press "Turn on camera", the code runs these steps:

  1. Check the page is secure (https) and the browser can use a camera.
  2. Ask for the front camera, ideally 1280 × 720. This is when the browser shows its permission prompt.
  3. Load the MediaPipe JavaScript, only now and not before. Visitors who only read the page download nothing heavy.
  4. Download the 13.5 MB engine and the 8.4 MB hand model piece by piece, updating the progress bar ("Downloading the AI models · 5.2 of 20.9 MB"). The engine is handed to MediaPipe from memory, so it isn't downloaded twice.
  5. Start the hand model, trying the graphics chip first and then the processor.
  6. Clear the sample cat drawing and begin.

Privacy

  • The video never leaves your device. The models run inside the browser tab, and the code makes no network request with video, sound or drawings in it.
  • The microphone is used only after you turn on Fog, and only for loudness. Nothing is recorded or kept.
  • Snapshots go into the tray on the page. Tapping one saves it to your own Downloads folder.
  • Leaving the page or pressing "Stop camera" turns off the camera and microphone.

When something goes wrong

What happens What you see
Camera permission refused "Camera access was blocked…" plus Try again and Play with mouse
No camera found "No camera was found on this device…" plus Play with mouse
Camera busy in another app "The camera could not start… It may be in use by another app"
Page opened without https "The camera only works on a secure (https) page…"
Model fails to download or start "The hand model could not load…" plus the reason
Microphone refused (Fog) "Microphone blocked. Hold the 9 key to fog the glass instead"

7. Testing, what isn't tested yet, and what to tune

Tested automatically (12 tests, run by GitHub before every publish):

  • The rules read the stick hand correctly: point, two fingers, palm, fist and pinch each get the right tool, and two L hands make a frame.
  • MediaPipe's answer wins, except that a pinch beats it unless it's a fist.
  • The 3-frame wait, the One Euro smoothing, the lighter flick (fires once, and not while just holding a thumbs up), and blowing (needs loud sound and pursed lips together).
  • The mirror maths: a point on the left of the raw camera picture lands on the right of the screen.
  • Every file the page loads exists, the model file sizes match what the progress bar expects, and every Google file still matches its fingerprint.

Tested in a browser: the page ran in Chrome with a fake camera, which shows a moving green test pattern. The models downloaded, started and ran on every frame. Fog loaded the microphone and the face model, and snapshots worked, with no errors.

Not tested yet: a real hand. The fake camera never shows a hand, so the gestures haven't been tried on a real person yet. The numbers below are first guesses. They are the knobs to turn after trying it for real.

Knob Now Turn it if… Where
Pinch distance 0.28 palm sizes Pinches are missed, or drawing turns into pinching PINCH_RATIO in gestures.mjs
Frames before a tool switches 3 Stray marks when changing shape (raise) or tools feel slow (lower) Debouncer(3) in air-ink.js
Smoothing 1.2 and 0.015 Lines wobble (lower the 1.2) or lag behind the finger (raise the 0.015) PointFilter in air-ink.js
Flick size 0.3 palm sizes in 0.5 s The flame won't light (lower) or lights by accident (raise) FlickDetector in gestures.mjs
Blow loudness 4 × room noise Fog won't start (lower) or starts when you talk (raise) BlowDetector in gestures.mjs
Lip score 0.3 Fog won't start with pursed lips (lower) BlowDetector in gestures.mjs
Frame hold 1 s Frames capture too soon or too late frameStep in air-ink.js
Hold times fist 1.5 s, thumbs up 1.2 s, thumbs down 0.5 s Actions fire by accident or feel slow the gesture list G in air-ink.js

Known limits. Hand tracking gets worse in dim light, with busy backgrounds, or when one hand covers the other. On slow computers the model may take longer than 33 ms, so the mirror updates less often. And holding a thumbs up for 1.2 s before flicking will take a snapshot before the flame lights.

Part 2 · The code, with notes

These are the most important parts of the real code, in the order they run. Every line starting with // is a note in plain English. Most of the notes were added for this page; the real files have fewer. To keep it readable, some long lines are split and less important parts are left out. Where a part is left out you'll see …, and a few bits (like where the fog starts) are slightly simplified. The full files show the exact code: air-ink.js (the main program, 770 lines), gestures.mjs (the rules, 129 lines) and hand.mjs (the mouse-mode hand, 95 lines).

A few words you'll see often:

  • P is one hand: a list of 21 points. P[8] is the index fingertip, P[4] the thumb tip, P[0] the wrist. Each point is [x, y] in screen pixels.
  • const and let create a named value. function creates a named set of steps. => is a short way to write a small function.
  • st holds the state of the mirror (current tool, colour, whether you're drawing). live holds the camera-mode things (the video, the models, the timers).
  • ix, fx and ux are the pens for the ink, fog and top layers. vx is the pen for the video layer.

8. Starting the camera and loading the models

File: air-ink.js. This runs when you press "Turn on camera". The word async means the function can pause and wait (for a download or a permission prompt) without freezing the page. await is where it waits.

// The list of big files, with their exact sizes so the progress bar knows the total.// A test checks these sizes still match the real files.export const FILES = {  bundle: new URL('./vendor/vision_bundle.mjs', import.meta.url).href,      // MediaPipe's JavaScript  loader: new URL('./vendor/wasm/vision_wasm_internal.js', import.meta.url).href,  wasm:  {url: new URL('./vendor/wasm/vision_wasm_internal.wasm', import.meta.url).href, bytes: 13519922}, // the engine  hands: {url: new URL('./models/gesture_recognizer.task', import.meta.url).href, bytes: 8373440},        // hand model  face:  {url: new URL('./models/face_landmarker.task', import.meta.url).href, bytes: 3758596}            // face model (Fog only)}; // Load MediaPipe's code, then download the engine ourselves so we can show progress.async function loadEngine(onBytes) {  // import() loads the 156 KB JavaScript only now, not when the page opens.  if (!live.vision) live.vision = await import(FILES.bundle);  if (!live.fileset) {    const wasm = await fetchBytes(FILES.wasm, onBytes);   // 13.5 MB, reports each chunk to the progress bar    // Hand the downloaded engine to MediaPipe from memory (a "blob" link), so it isn't downloaded twice.    live.fileset = {wasmLoaderPath: FILES.loader,      wasmBinaryPath: URL.createObjectURL(new Blob([wasm], {type: 'application/wasm'}))};  }} // Start a model. Try the graphics chip (GPU) first; if that fails, use the processor (CPU).async function createTask(Task, buffer, options) {  let err;  for (const delegate of ['GPU', 'CPU']) {    try {      const task = await Task.createFromOptions(live.fileset, {        baseOptions: {modelAssetBuffer: buffer, delegate},  // the model file we downloaded        runningMode: 'VIDEO',   // VIDEO mode lets it track between frames, so the palm detector can rest        ...options});      if (!live.delegate) live.delegate = delegate;   // remember GPU or CPU, shown on the camera tag      return task;    } catch (e) { err = e; }    // GPU failed: loop round and try CPU  }  throw err;                    // both failed: give up and show an error} async function startCamera() {  // The browser only allows cameras on https pages.  if (!window.isSecureContext || !navigator.mediaDevices?.getUserMedia) { startError('The camera only works on a secure (https) page…'); return; }  showStart('loading'); progress('Asking for your camera…', null);  try {    // This line makes the browser show its "Allow camera?" prompt. Front camera, ideally 1280 × 720.    live.stream = await navigator.mediaDevices.getUserMedia({video: {facingMode: 'user', width: {ideal: 1280}, height: {ideal: 720}}, audio: false});  } catch (e) {    // Different messages for "blocked", "no camera" and "camera busy".    startError(e.name === 'NotAllowedError' ? 'Camera access was blocked…' : e.name === 'NotFoundError' ? 'No camera was found…' : 'The camera could not start…');    return;  }  // … the video starts playing (hidden), then the models download:  const total = FILES.wasm.bytes + FILES.hands.bytes; let got = 0;  const onBytes = n => { got += n; progress(`Downloading the AI models · ${MB(got)} of ${MB(total)} MB`, got / total); };  await loadEngine(onBytes);  const model = await fetchBytes(FILES.hands, onBytes);  progress('Warming up the hand model…', 1);  live.gesture = await createTask(live.vision.GestureRecognizer, model, {    numHands: 2,                       // track up to two hands (needed for the Frame gesture)    minHandDetectionConfidence: .6,    // how sure the palm detector must be to report a hand    minHandPresenceConfidence: .5,     // below this, the hand counts as lost    minTrackingConfidence: .5});  // … then the sample cat drawing is cleared and camera mode begins.}

9. The heartbeat: one frame

File: air-ink.js. requestAnimationFrame asks the browser to call frame again before the next screen refresh, about 60 times a second. That is the loop that keeps everything moving.

let lastT = performance.now();function frame(t) {                               // t = the time now, in milliseconds  const dt = Math.min(.05, (t - lastT) / 1000);   // seconds since the last frame (capped, in case the tab was hidden)  lastT = t;  if (W) st.mode === 'camera' ? cameraFrame(dt, t) : mouseFrame(dt, t);   // real hand, or mouse hand  requestAnimationFrame(frame);                   // "call me again next refresh"}requestAnimationFrame(frame);                     // start the loop

This is the camera-mode frame, shortened to its main steps.

function cameraFrame(dt, t) {  const v = live.video;  if (!v || v.readyState < 2) return;             // the camera isn't giving pictures yet   // STEP 1: draw the camera picture, flipped like a mirror.  const fit = coverFit(v.videoWidth, v.videoHeight, W, H);   // how big to draw it so it fills the screen  vx.save(); vx.translate(W, 0); vx.scale(-1, 1);            // scale(-1, 1) = flip left to right  vx.drawImage(v, fit.ox, fit.oy, fit.dw, fit.dh); vx.restore();   // STEP 2: run the hand model, but only when the camera has a NEW picture.  if (v.currentTime !== live.lastVideoTime) {    live.lastVideoTime = v.currentTime;    const t0 = performance.now();    const res = live.gesture.recognizeForVideo(v, t0);        // <- THE AI CALL. Returns points + shape names.    live.modelMs += ((performance.now() - t0) - live.modelMs) * .1;   // average model time, for the "ms" display     // STEP 3: turn each hand's 21 points into screen pixels, and keep MediaPipe's shape name.    live.hands = res.landmarks.map((lm, i) => ({      P: lm.map(p => toScreen(p, fit, W)),      gesture: res.gestures[i]?.[0]?.categoryName}));       // e.g. 'Pointing_Up'     // STEP 4: pick the tool, then wait for 3 frames in a row before switching.    const {tool, primary} = classify(live.hands);    const stable = live.debounce.push(tool);     // Lighter: only listen for a flick when the hand is in a thumb shape.    if (primary && (stable === 'up' || stable === 'fist' || stable === null)        && live.flick.update(t / 1000, primary.P)) live.fireLit = true;    if (['point', 'peace', 'palm', 'pinch', 'frame'].includes(stable)) live.fireLit = false;   // open hand = flame out    setPose(live.fireLit ? 'lighter' : stable);  }   // STEP 5: find the point the tool works at, smooth it, and act.  const P = live.primary.P, mode = POSES[st.pose].anchor;    // 'tip', 'pinch', 'palm' or 'L'  const a = live.anchor.filter(anchorOf(P, mode), t / 1000); // One Euro smoothing  act(a, dt, palmSize(P));                                   // draw / erase / drag / hold timers   // STEP 6: effects and the top layer.  st.blowing = live.fogOn ? live.blow.update({rms: micLevel(), pucker: live.pucker, dt}) : false;  updateFire(dt, P[4], live.fireLit, strike, s);             // flames at the thumb tip (point 4)  updateFog(dt, t);  if (st.showDots) live.hands.forEach(h => drawDots(ux, h.P, palmSize(h.P)));   // the 21 white dots  setStatus(label, st.pose);                                 // the "Drawing" chip}

In the real file, step 5 also handles the two-hand Frame (section 16), and there are checks for when no hand is visible.

10. Putting the 21 points on the screen

File: gestures.mjs. The model gives each point as fractions of the raw camera picture (x and y from 0 to 1). The screen is a different shape and is shown mirrored, so the code converts.

// How to draw a vw × vh camera picture so it COVERS a W × H screen (no black bars, edges cut off).export function coverFit(vw, vh, W, H) {  const s = Math.max(W / vw, H / vh);   // the bigger scale wins, so both sides are filled  const dw = vw * s, dh = vh * s;       // drawn width and height (may be bigger than the screen)  return {dw, dh, ox: (W - dw) / 2, oy: (H - dh) / 2};   // ox, oy = offsets that centre it (often negative)} // One landmark {x, y} (0 to 1) -> screen pixels [x, y].// "W - ..." flips x, because the picture on screen is a mirror image.export const toScreen = (lm, fit, W) => [W - (fit.ox + lm.x * fit.dw), fit.oy + lm.y * fit.dh];

Example: a 1280 × 720 camera on an 800 × 800 screen. The scale is 800 / 720 = 1.11, so the picture is drawn 1422 wide and 311 pixels hang off each side. A fingertip at x = 0.5 lands in the middle (400). A fingertip at x = 0.3 on the raw picture (your right hand, which the camera sees on its left) lands at about 684, on the right of the screen, just like a mirror. A test checks exactly this.

11. Choosing the tool

File: gestures.mjs. These are the rules from section 5, as code. dist(a, b) is the straight-line distance between two points.

// Palm size = wrist (0) to middle-finger knuckle (9). Every rule measures in palm sizes,// so it works whether your hand is near the camera (big) or far away (small).export const palmSize = P => dist(P[0], P[9]) || 1; // Which fingers are straight?export function fingerStates(P) {  const w = P[0];  // A finger is straight when its tip is at least 12% further from the wrist than its middle joint.  const straight = (tip, pip) => dist(w, P[tip]) > dist(w, P[pip]) * 1.12;  return {    // The thumb is "out" when its tip is away from the index knuckle and further from the pinky than its own joint.    thumb: dist(P[4], P[5]) / palmSize(P) > .55 && dist(P[4], P[17]) > dist(P[3], P[17]),    index: straight(8, 6), middle: straight(12, 10), ring: straight(16, 14), pinky: straight(20, 18)  };} // Pinch: thumb tip (4) to index tip (8), in palm sizes. Under 0.28 = pinching.export const pinchRatio = P => dist(P[4], P[8]) / palmSize(P);export const PINCH_RATIO = .28; // An L: index and thumb straight, middle and ring folded, at roughly a right angle.export function isL(P) {  const f = fingerStates(P);  if (!f.index || !f.thumb || f.middle || f.ring) return false;  const a = [P[8][0] - P[5][0], P[8][1] - P[5][1]];   // direction of the index finger  const b = [P[4][0] - P[2][0], P[4][1] - P[2][1]];   // direction of the thumb  // The angle between the two directions, in degrees (school trigonometry: the "dot product").  const cos = (a[0] * b[0] + a[1] * b[1]) / (Math.hypot(...a) * Math.hypot(...b) || 1);  const deg = Math.acos(Math.max(-1, Math.min(1, cos))) * 180 / Math.PI;  return deg > 55 && deg < 125;                      // 90° is a perfect L; we allow 35° either way} // MediaPipe's names -> our tool names.const CANNED = {Pointing_Up: 'point', Victory: 'peace', Open_Palm: 'palm',                Closed_Fist: 'fist', Thumb_Up: 'up', Thumb_Down: 'down'}; // The tool for ONE hand. Checks run top to bottom; the first match wins.export function toolFor(P, gesture) {  if (gesture !== 'Closed_Fist' && pinchRatio(P) < PINCH_RATIO) return 'pinch';   // 1. pinch (not in a fist)  if (CANNED[gesture]) return CANNED[gesture];                                     // 2. MediaPipe's answer  const f = fingerStates(P);                                                       // 3. our own backup  if (f.index && !f.middle && !f.ring && !f.pinky) return 'point';  if (f.index && f.middle && !f.ring && !f.pinky) return 'peace';  if (f.index && f.middle && f.ring && f.pinky) return 'palm';  if (!f.index && !f.middle && !f.ring && !f.pinky) return 'fist';  return null;                                                                     // a shape we don't know} // The tool for THIS FRAME, looking at all hands.export function classify(hands) {  if (!hands.length) return {tool: null, primary: null};                 // no hands  if (hands.length >= 2 && isL(hands[0].P) && isL(hands[1].P))    return {tool: 'frame', primary: hands[0]};                           // two L hands = Frame  // Otherwise the biggest hand (usually the closest) decides.  const primary = hands.reduce((a, b) => palmSize(b.P) > palmSize(a.P) ? b : a);  return {tool: toolFor(primary.P, primary.gesture), primary};}

12. Steadiness: waiting 3 frames and smoothing

File: gestures.mjs. A class is a little machine that remembers things between frames. new Debouncer(3) builds one; push feeds it the latest reading.

// Only switch tool after the same reading comes `frames` times in a row.export class Debouncer {  constructor(frames = 3) { this.frames = frames; this.stable = null; this.cand = undefined; this.run = 0; }  push(v) {    if (v === this.cand) this.run++;          // same as last time: count up    else { this.cand = v; this.run = 1; }     // something new: start counting again    if (this.run >= this.frames) this.stable = v;   // seen 3 times in a row: switch    return this.stable;                       // the tool actually used  }} // One Euro filter (Casiez, Roussel and Vogel, 2012). Smooths one number, such as a fingertip's x.export class OneEuro {  constructor({minCutoff = 1.2, beta = .015, dCutoff = 1} = {}) { /* … stores the three settings */ }  // How much of the new reading to take: a number between 0 and 1.  static alpha(cutoff, dt) { const r = 2 * Math.PI * cutoff * dt; return r / (r + 1); }  filter(x, t) {    if (this.x === null) { this.x = x; this.t = t; return x; }   // first reading: take it as it is    const dt = Math.max(1e-3, t - this.t); this.t = t;    const dx = (x - this.x) / dt;                                // how fast it is moving    this.dx += OneEuro.alpha(this.dCutoff, dt) * (dx - this.dx); // (speed is smoothed a little too)    // THE KEY LINE: slow movement -> low cutoff -> heavy smoothing.    //               fast movement -> high cutoff -> light smoothing, so no lag.    const cutoff = this.minCutoff + this.beta * Math.abs(this.dx);    this.x += OneEuro.alpha(cutoff, dt) * (x - this.x);         // move part of the way to the new reading    return this.x;  }} // A point has an x and a y, so PointFilter is just two OneEuro filters side by side.export class PointFilter {  constructor(opts) { this.fx = new OneEuro(opts); this.fy = new OneEuro(opts); }  filter(p, t) { return [this.fx.filter(p[0], t), this.fy.filter(p[1], t)]; }}

To make lines steadier, lower minCutoff (1.2). To make the pen keep up with fast moves, raise beta (0.015).

13. Drawing a line, erasing, and writing in the mist

File: air-ink.js, inside the function act. a is the smoothed point, s is the palm size on screen. st.last is where the pen was on the previous frame; null means the pen has just been put down.

if (st.pose === 'point') {                                      // DRAW tool  if (overBar) { st.last = null; label = 'Pen lifted over toolbar'; }   // never draw over the buttons   else if (st.wipe || (st.fogged && fogAt(a) > 40)) {          // finger is on fogged glass?    // Instead of drawing, rub the fog away: "destination-out" makes pixels see-through.    fx.save(); fx.globalCompositeOperation = 'destination-out';    fx.lineCap = 'round'; fx.lineWidth = s * .28;             // a stripe about a finger wide    const from = st.wipe || a;    fx.beginPath(); fx.moveTo(from[0], from[1]); fx.lineTo(a[0] + .01, a[1]); fx.stroke(); fx.restore();    st.wipe = a; label = 'Writing in the mist';  }   else if (!st.last) {                                         // pen just touched down    pushUndo();                                                // save a copy for Undo first    st.last = a; st.midPrev = a; dab(a);                       // put a dot where the line starts  }   else if (dist(a, st.last) > 1.2) {                           // moved more than 1.2 pixels: draw    const m = lerp(st.last, a, .5);                            // halfway between the last point and this one    ix.save();    ix.strokeStyle = st.color;                                 // the colour you picked    ix.lineWidth = strokeWidth(st.size, W, H);                 // thin / medium / thick, scaled to the screen    ix.lineCap = ix.lineJoin = 'round';    ix.shadowColor = st.color; ix.shadowBlur = ix.lineWidth * 1.2;   // the neon glow    // A smooth curve: from the last halfway point, bending through the last point, to the new halfway point.    ix.beginPath(); ix.moveTo(st.midPrev[0], st.midPrev[1]);    ix.quadraticCurveTo(st.last[0], st.last[1], m[0], m[1]);    ix.stroke(); ix.restore();    st.midPrev = m; st.last = a;                               // remember for the next frame  } } else if (st.pose === 'palm') {                               // ERASE tool  const r = s * .95;                                           // eraser radius: about one palm  if (!st.erasing) { pushUndo(); st.erasing = a; }  ix.save(); ix.globalCompositeOperation = 'destination-out';  // cut holes in the INK layer only  ix.lineCap = 'round'; ix.lineWidth = r * 2;  ix.beginPath(); ix.moveTo(st.erasing[0], st.erasing[1]); ix.lineTo(a[0] + .01, a[1]); ix.stroke(); ix.restore();  st.erasing = a;}

The eraser draws a thick line from where the palm was to where it is now, so a fast swipe leaves no gaps.

14. Fire: spotting the lighter flick

File: gestures.mjs. A flick is a movement, so this machine keeps a short history: the last half second of one number, v, which says how low the thumb tip is compared with the index knuckle.

export class FlickDetector {  constructor({drop = .3, window = .5} = {}) { this.drop = drop; this.window = window; this.h = []; }  update(t, P) {    // v = how far the thumb tip (4) is BELOW the index knuckle (5), in palm sizes.    // (On screens, y grows downwards, so a bigger v means the thumb is lower.)    const v = (P[4][1] - P[5][1]) / palmSize(P);    this.h.push({t, v});                                                   // add to the history    while (this.h.length && t - this.h[0].t > this.window) this.h.shift(); // forget anything older than 0.5 s     // Find the lowest the thumb went (the peak of v) in the history…    let peak = 0;    for (let i = 1; i < this.h.length; i++) if (this.h[i].v > this.h[peak].v) peak = i;    // …and where it started before that.    const before = Math.min(...this.h.slice(0, peak + 1).map(s => s.v));    const top = this.h[peak].v;     // A flick = the thumb went DOWN by more than 0.3 palm sizes, then came back UP by at least 0.24.    if (peak > 0 && peak < this.h.length - 1 && top - before > this.drop && top - v > this.drop * .8) {      this.h = [];        // clear the history so one flick lights the flame only once      return true;        // FLICK!    }    return false;  }}

The flame itself is in air-ink.js (updateFire and drawFire). Each frame it adds 4 glowing dots at the thumb tip with an upward speed, moves every dot, and shrinks each dot's life from 1 to 0. Its colour depends on life: pale yellow when new, orange in the middle, red at the end. The strike also adds 14 "spark" dots that fly out and fall with gravity.

15. Fog: listening for a blow

Three pieces work together: the microphone gives loudness, the face model gives the lip scores, and BlowDetector decides. Then updateFog paints.

Opening the microphone (air-ink.js, in toggleFog):

// Turn OFF the browser's voice clean-up. It is built to remove breath noise, which is exactly what we need.live.mic = await navigator.mediaDevices.getUserMedia({audio:  {echoCancellation: false, noiseSuppression: false, autoGainControl: false}});live.audio = new AudioContext();live.analyser = live.audio.createAnalyser();          // a tool that lets us read the raw sound wavelive.analyser.fftSize = 1024;                          // look at 1024 sound samples at a timelive.audio.createMediaStreamSource(live.mic).connect(live.analyser); // Loudness each frame: the "root mean square" of the wave (square each sample, average, square root).function micLevel() {  live.analyser.getFloatTimeDomainData(live.buf);  let s = 0; for (const v of live.buf) s += v * v;  return Math.sqrt(s / live.buf.length);              // 0 = silence, about 0.3+ = very loud}

Reading the lips (air-ink.js, inside cameraFrame, every second frame):

const f = live.face.detectForVideo(v, performance.now());      // <- THE FACE AI CALLconst shapes = f.faceBlendshapes?.[0]?.categories || [];        // the 52 expression scoresconst score = n => shapes.find(c => c.categoryName === n)?.score || 0;live.pucker = Math.max(score('mouthPucker'), score('mouthFunnel'));   // the higher of the two lip scoresconst lm = f.faceLandmarks?.[0];                                // the 478 face points// The fog starts halfway between point 13 (upper lip) and point 14 (lower lip).st.mouth = lm ? mid(toScreen(lm[13], fit, W), toScreen(lm[14], fit, W)) : null;

Deciding (gestures.mjs):

export class BlowDetector {  constructor() { this.floor = .01; this.on = 0; this.off = 0; this.active = false; }  update({rms, pucker, dt}) {    // Learn the room's normal noise level slowly (2% per frame), but only while NOT blowing.    if (!this.active) this.floor += (Math.min(rms, this.floor * 3) - this.floor) * .02;    const loud = rms > Math.max(.03, this.floor * 4);   // 4× the room, and never below 0.03    const lips = pucker > .3;                           // lips pursed or rounded    if (loud && lips) { this.on += dt; this.off = 0; }  // both clues: count time up    else { this.off += dt; this.on = 0; }    if (!this.active && this.on > .2) this.active = true;    // 0.2 s of both = start fogging    if (this.active && this.off > .25) this.active = false;  // 0.25 s without = stop    return this.active;  }}

Painting the fog (air-ink.js):

function updateFog(dt, t) {  if (st.blowing) {    st.blowT += dt; st.lastBlow = t; st.fogged = true;    const m = st.mouth;                                  // start at your mouth    // The cloud grows the longer you blow, up to 80% of the screen.    const R = Math.min(Math.max(W, H) * .8, Math.min(W, H) * .12 + st.blowT * Math.max(W, H) * .3);    const g = fx.createRadialGradient(m[0], m[1], 0, m[0], m[1], R);   // soft circle: white middle, clear edge    g.addColorStop(0, 'rgba(228,234,233,.15)'); g.addColorStop(.55, 'rgba(222,229,228,.07)'); g.addColorStop(1, 'rgba(222,229,228,0)');    fx.fillStyle = g; fx.fillRect(0, 0, W, H);           // add a thin layer each frame, so it builds up  } else if (st.fogged) {    if (t - st.lastBlow > 20000) { fx.clearRect(0, 0, W, H); st.fogged = false; }   // 20 s later: all gone    else if ((fogTick += dt) > .3) {                     // every 0.3 s: wipe away 4.5% of the fog      fogTick = 0;      fx.save(); fx.globalCompositeOperation = 'destination-out'; fx.fillStyle = 'rgba(0,0,0,.045)'; fx.fillRect(0, 0, W, H); fx.restore();    }  }}

16. Frame: the two-hand screenshot

When both hands make an L shape, each hand gives one corner. Hold the box still for one second and it saves a picture.

One corner per hand (gestures.mjs):

// The corner sits halfway between point 2 (the thumb's lower knuckle) and point 5 (the index knuckle),// which is the inside bend of the L.export const lCorner = P => mid(P[2], P[5]);

Following both corners (air-ink.js, inside cameraFrame):

} else if (st.pose === 'frame' && hands.length >= 2) {  // Each corner gets its own One Euro filter, so the box does not shake.  const c1 = live.corners[0].filter(lCorner(hands[0].P), t / 1000);  const c2 = live.corners[1].filter(lCorner(hands[1].P), t / 1000);  // Speed = how far the faster corner moved since last frame, in pixels per second.  const speed = live.prevCorners    ? Math.max(dist(c1, live.prevCorners[0]), dist(c2, live.prevCorners[1])) / Math.max(dt, 1e-3) : 0;  live.prevCorners = [c1, c2];  const f = frameStep(c1, c2, dt, speed); R = f.R; label = f.label;   // R = the box to draw, label = the hint text}

Deciding when to capture (air-ink.js):

// Two opposite corners make a box: [left, top, right, bottom].const rectOf = (a, b) => [Math.min(a[0], b[0]), Math.min(a[1], b[1]), Math.max(a[0], b[0]), Math.max(a[1], b[1])]; function frameStep(a, b, dt, speed) {  const R = rectOf(a, b);  // Hands too close together: no box yet.  if (R[2] - R[0] < 40 || R[3] - R[1] < 40) { st.rectStill = 0; return {R: null, label: 'Open the frame wider'}; }  // Already took one: wait until you drop your hands, so it does not keep snapping.  if (st.latched) return {R, label: 'Saved · drop your hands to frame again'};  // "Still" = corners moving slower than 15% of the screen per second. Count up while still, reset if not.  st.rectStill = speed < Math.min(W, H) * .15 ? st.rectStill + dt : 0;  if (st.rectStill >= 1) { captureRect(R); st.latched = true; }   // 1 full second still = click!  return {R, label: 'Hold still to capture'};}

Taking the picture (air-ink.js):

function captureRect(r) {  const w = r[2] - r[0], h = r[3] - r[1]; if (w < 24 || h < 24) return false;  // Make a new, invisible canvas the size of the box (at most 1200 px wide, to keep files small).  const sc = Math.min(DPR, 1200 / w), c = document.createElement('canvas');  c.width = Math.round(w * sc); c.height = Math.round(h * sc);  const x = c.getContext('2d');  // Copy the same box from each layer, bottom to top: camera video, then your ink, then the fog.  // (DPR = how many real screen pixels make one CSS pixel; phones are often 2 or 3.)  for (const src of [vC, iC, fC]) x.drawImage(src, r[0] * DPR, r[1] * DPR, w * DPR, h * DPR, 0, 0, c.width, c.height);  addToTray(c, true, 'Framed picture saved');   // turn it into a JPEG, add it to the tray, flash the screen  return true;}

The tray keeps the four newest pictures. Each one is a link that downloads as air-ink-frame-N.jpg. Nothing is uploaded: the picture only lives in your browser until you save it.

Dee Bee