Interactive Vision From Zero · Episode 12
Face Mesh & AR Filters
Face Mesh & AR Filters is Episode 12 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 .
Snapchat's whole empire — the dog ears, the flower crown, the face-swap, the puppy nose that boops when you open your mouth — is, underneath the magic, a list of 468 dots stuck to your face. A model finds them sixty times a second, and a filter is nothing more than a sprite pinned to a few of those dots, scaled by how big your face is and rotated to match how your head is tilted. That's it. The billion-dollar feature is an anchor, a scale, and an angle.
This episode builds AR face filters in about fifty lines. Below, a glowing face mesh is already wearing glasses, a crown, and a mask — and the face is synthetic, animated by math, so the page is alive the instant it loads with no webcam and nothing downloaded. The head yaws side to side; the eyes blink. Move your mouse to drag it around. When you're ready, click use my camera and the exact same glasses snap onto your face — because everything downstream of the landmarks can't tell synthetic dots from real ones.
🔒 The camera button runs the model entirely in your
browser. No frame is ever uploaded; nothing leaves your machine.
Until you press it, the demo uses a synthetic face and makes zero network requests.
What you're looking at
A face, reduced to a handful of glowing landmarks, wearing graphics that track it. That's the end state of face landmark detection: MediaPipe's Face Landmarker looks at an image and returns 468 points — a dense mesh blanketing the whole face, every eyelid and lip contour and cheek. It's a flood of data compared to the 21-point hand. The trick to staying sane is to not use all 468. You reach into the array for the dozen named features you actually need — the eye corners, the nose tip, the chin, the forehead — and build your filters off those.
Step the stage dropdown through the six views to watch a filter get built one decision at a time: first the raw features, then a sprite anchored to them, then scaled, then rotated, then a second filter, then all of them swappable live with the filter dropdown. Every stage is the same machine showing one more layer.
The 468-point mesh, taught by its landmarks
You will never memorize 468 indices, and you don't need to. The entire series of face demos rides on maybe fifteen of them. Here is the working set — the named landmarks every filter in this episode anchors to. Pin this table; it's the face equivalent of the hand's 21-point map:
Two pairs do almost all the heavy lifting. The eye centers — the
average of each eye's inner and outer corner (33/133 and
362/263) — give you a stable line across the face that tells you
where to put glasses, how wide to make them, and what angle the head is tilted at. And the
distance between those two eye centers, the interocular distance, is your
universal ruler: it's how you scale every filter so it fits a face two feet away exactly
as well as one six feet away. Get comfortable with the eye line and you can build any
filter.
Stage 1 — The face features
Before anything wears anything, look at the skeleton. This stage draws only the named landmarks — the two eyes, the nose tip, the mouth corners, the chin and forehead, and a rough face oval — pulled straight out of the mesh. On the synthetic face these come from a little struct; on the camera path they're read from the real 468-array by index. Either way the picture is identical, because a filter never sees pixels — it sees these dots.
Stage 2 — Glasses
The "hello world" of AR. We take the two eye centers, find the midpoint between them, and draw a pair of glasses there: two lenses sitting over the eyes, a bridge across the nose, arms running back toward the ears. Right now the glasses are a fixed size and sit flat — anchored, but naive. Notice they already stick to the eyes as the face drifts. Anchoring is the first and most important move.
Stage 3 — Crown
A crown belongs above the face, anchored to the forehead landmark
(10). But how big should it be? If we used a fixed pixel width it'd swallow a
distant face and look like a toy on a close one. So we scale it by the
interocular distance — the span between the eyes. Lean toward the
camera (or, in synthetic mode, watch it breathe) and the crown grows and shrinks to stay
proportional. Scale-by-eye-distance is the rule that makes filters feel glued on.
Stage 4 — Rotate with the head
Tilt your head and flat glasses look broken instantly — they should tilt with you. The
fix is one number: the angle of the eye line,
atan2(rightEye.y − leftEye.y, rightEye.x − leftEye.x). Rotate every filter by
that angle around its anchor and the glasses, crown, and mask all bank with your head.
This stage drives the synthetic face into an exaggerated yaw/tilt so you can see the
filters follow. The eye-line angle is the cheapest, most robust "head rotation" you can
get from 2D landmarks.
Stage 5 — Mask
A different anchor for a different filter. A mask covers the lower face, so we
build it from the mouth corners (61/291) and the chin
(152): a rounded shape spanning corner to corner and dropping to the jaw,
scaled by the same interocular ruler and rotated by the same eye-line angle. Open your
mouth and the mask's mouth-slit opens with it (we read the lip gap,
13↔14). Same three primitives — anchor, scale, rotate — pointed
at a different part of the face.
Stage 6 — Swappable filters
Now it's a real app. Use the filter dropdown to pick glasses, crown, or mask — or all to stack them. Because every filter is just a function that takes the face struct and draws itself, swapping or stacking is trivial: keep a list of active filters and call each one. This is exactly how a production AR pipeline works — a registry of filters, each anchored to landmarks, all fed by one tracker. Draw order matters: the mask goes on first (behind), the glasses and crown on top.
How the code works
The architecture is the same one this whole series leans on: one
onLandmarks(face) path serves both the synthetic face and the real
camera. The catch unique to faces is the shape of face. The synthetic driver
hands us a tidy named-feature struct directly; the camera hands us a raw 468-element
array. So the very first thing the camera path does is build the same struct by
indexing the array. After that line, nothing downstream knows or cares which it got.
(a) Extracting the named features
The synthetic generator (from the authoring brief) returns a struct with
leftEye, rightEye, forehead, chin,
mouth, and yaw already named. The camera path produces the
identical struct from lm[33], lm[133],
lm[10], and friends. Eye centers are the average of the inner and
outer corner; blink and mouth-open fall out of two more distances:
// Synthetic: already a named struct (blink + head yaw animated).
// face.leftEye.c, face.rightEye.c, face.forehead, face.chin, face.mouth, face.yaw
// Camera: build the SAME struct from the raw 468-array by index.
const avg = (a, b) => ({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 });
const dist = (a, b) => Math.hypot(a.x - b.x, a.y - b.y);
function faceFromMesh(lm) { // lm = result.faceLandmarks[0] (468 pts)
const leftC = avg(lm[33], lm[133]); // left eye outer+inner
const rightC = avg(lm[362], lm[263]); // right eye inner+outer
return {
noseTip: lm[1], forehead: lm[10], chin: lm[152],
leftEye: { c: leftC, open: dist(lm[159], lm[145]) }, // lid gap → blink
rightEye: { c: rightC, open: dist(lm[386], lm[374]) },
mouth: { c: avg(lm[61], lm[291]), open: dist(lm[13], lm[14]) },
mouthL: lm[61], mouthR: lm[291],
};
}
(b) Anchoring glasses between the eyes
Every filter reduces to three numbers off the eye line: a position
(the midpoint between the eye centers), a width (proportional to the gap
between them), and an angle (the tilt of the line). Compute those once,
then draw the glasses in a local frame. The mirror flip lives in
toPixel so the math here is clean:
// Eye centers → pixels (mirror-flipped for the selfie view).
const L = toPixel(face.leftEye.c, W, H);
const R = toPixel(face.rightEye.c, W, H);
const cx = (L.x + R.x) / 2, cy = (L.y + R.y) / 2; // anchor: between the eyes
const eyeDist = Math.hypot(R.x - L.x, R.y - L.y); // the universal ruler
const angle = Math.atan2(R.y - L.y, R.x - L.x); // head tilt from the eye line
ctx.save();
ctx.translate(cx, cy); // move to the anchor
ctx.rotate(angle); // bank with the head
const lens = eyeDist * 0.42; // everything sized off eyeDist, never px
ctx.beginPath(); ctx.arc(-eyeDist / 2, 0, lens, 0, Math.PI * 2); // left lens
ctx.arc( eyeDist / 2, 0, lens, 0, Math.PI * 2); // right lens
ctx.stroke();
ctx.restore();
(c) Scaling by interocular distance + rotating by the eye-line angle
This is the heart of "it sticks." Never use absolute pixels for a filter's
size — use eyeDist as the unit, and everything auto-fits any face at any
distance. Pair that with the eye-line angle for rotation and you have a
reusable anchor any filter can sit in. The crown is the same pattern aimed at the
forehead:
// A reusable local frame: anchor + scale (eyeDist) + rotation (angle).
function withAnchor(ctx, anchorPx, eyeDist, angle, draw) {
ctx.save();
ctx.translate(anchorPx.x, anchorPx.y);
ctx.rotate(angle);
draw(ctx, eyeDist); // draw in units of eyeDist, centered on the anchor
ctx.restore();
}
// Crown: anchored to the forehead, sized by the eye gap, tilted with the head.
const fore = toPixel(face.forehead, W, H);
withAnchor(ctx, fore, eyeDist, angle, (c, u) => {
const w = u * 1.6, h = u * 0.9; // crown size scales with the face
c.beginPath();
c.moveTo(-w/2, 0);
for (let i = 0; i <= 4; i++) { // five zig-zag points
const x = -w/2 + (w * i) / 4;
c.lineTo(x - w/8, -h); // spike up
c.lineTo(x, -h * 0.35); // dip down
}
c.closePath(); c.fill();
});
(d) The FaceLandmarker, loaded lazily
MediaPipe is never imported at the top of the file — only inside the
camera button's handler, wrapped in try/catch so any failure (no webcam,
denied permission, file://) falls back to the synthetic face instead of
throwing. The Face Landmarker reads result.faceLandmarks[0], the 468-array we
feed straight into faceFromMesh:
const MP_URL = 'https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.18';
const MP_WASM = MP_URL + '/wasm';
const FACE_TASK = 'https://storage.googleapis.com/mediapipe-models/' +
'face_landmarker/face_landmarker/float16/1/face_landmarker.task';
async function enableCamera() {
try {
setStatus('loading model… (first time downloads a few MB)');
const { FaceLandmarker, FilesetResolver } = await import(/* @vite-ignore */ MP_URL);
const fileset = await FilesetResolver.forVisionTasks(MP_WASM);
landmarker = await FaceLandmarker.createFromOptions(fileset, {
baseOptions: { modelAssetPath: FACE_TASK, delegate: 'GPU' },
runningMode: 'VIDEO', numFaces: 1, outputFaceBlendshapes: false,
});
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
}
}
// In the loop: res = landmarker.detectForVideo(video, performance.now());
// const lm = res.faceLandmarks?.[0]; face = lm ? faceFromMesh(lm) : null;
Common pitfalls
- Filters jitter and swim. You anchored to a wobbly landmark — the outer face-oval points and cheeks are noisy. Anchor to stable features instead: the eye corners and the line between the eye centers barely move frame to frame. Build the whole filter off the eye line and the jitter mostly vanishes.
- The glasses are right for one distance and wrong for every other.
You sized the filter in absolute pixels. Always scale by the interocular
distance (
eyeDist) — then a face near or far gets glasses that fit. Pixels are never the unit; the eye gap is. - Tilt your head and the filter stays level. You forgot to rotate.
Take the eye-line angle with
atan2(R.y − L.y, R.x − L.x)andctx.rotatethe filter by it. A 2D eye-line angle is enough for convincing head-tilt; you don't need full 3D pose. - Everything's backwards in the selfie view. Same mirror gotcha as
the hand episodes: map
xas(1 - lm.x) * widthso moving right moves the on-screen face right. Apply it in both synthetic and camera modes. - You grabbed the wrong index. The 468-map is unforgiving — fetch
lm[133]when you meantlm[33]and your eye center lands on the wrong corner. Keep the named-feature table handy and double-check every lookup; a single transposed index puts a lens on someone's cheek. - Draw order looks wrong. A mask drawn after the glasses paints over them. Decide the stack on purpose: mask behind, glasses and crown in front. With a filter registry, just order the list.
Exercises
- Dog ears + nose. Add a fourth filter: two triangular ears anchored
above the forehead (offset left/right by
eyeDist) and a black oval nose on the nose tip (1), all scaled byeyeDistand rotated by the eye angle. You now have the most-used Snapchat lens, in a dozen lines. - Tint the lips. Using the mouth corners (
61/291) and the upper/lower lip points (13/14), draw a translucent colored shape over the lips. Make the color slider-driven. This is the seed of a full AR makeup filter. - Face-distortion bulge. Sample the video frame into the canvas, then around the nose tip radially push pixels outward (a "bulge"): for each output pixel near the anchor, read from a point pulled toward the center. A cheap fish-eye that warps the real face — the basis of the wackier lenses.
What's next
Episode 13 — Gaze, Blink & Mouth as Controls. We stop decorating
the face and start listening to it: the same eye-aspect-ratio that we glossed over
here (leftEye.open) becomes a blink detector, the lip gap
(mouth.open) becomes a trigger, and the iris landmarks
(468/473) become a gaze pointer. The face stops being a canvas
and becomes a controller.