The look we wanted
Open any bridal portrait PSD from a big studio and you'll find the same trick: a huge title word, "Forever" or the couple's names, set behind the bride. The letters run across the background and disappear behind her shoulders and veil, so she seems to stand in front of the type.
In Photoshop that's a person cut out by hand on a layer above the text. We wanted it as a checkbox in the text tool that sits on top of "Apply TheRare look" (Part 14): type a word, pick one of the studio's fonts, tick Behind subject, and download.
That needs three things the browser doesn't do by itself: finding the people in a photo, drawing text in the studio's own fonts, and stacking the layers so the preview and the full-size download match exactly.
Finding the people, on the device
Cutting a person out of a photo is image segmentation: for every pixel, how likely is it that this pixel is part of a person? We use Google's MediaPipe with its multi-class selfie segmenter model. It's free (Apache-2.0), small, and runs in the browser as WebAssembly, so no photo leaves the device for this either.
The model doesn't answer "person or not". It returns a confidence for several categories: background, hair, body skin, face skin, clothes and so on. We only need one question answered, so we use the inverse of the background score:
// Category 0 is background; everything else (hair, body, face, clothes...) is the person.
const bg = result.confidenceMasks?.[0];
const conf = bg.getAsFloat32Array();
for (let i = 0; i < w * h; i++) {
const p = 1 - conf[i];
// Tighten the soft model edge a little so text doesn't ghost through hair and shoulders.
const t = Math.min(1, Math.max(0, (p - 0.3) / 0.4));
const a = t * t * (3 - 2 * t);
img.data[i * 4 + 3] = Math.round(a * 255);
}The last three lines matter more than they look. The model's edges are soft, which is good for hair, but a pixel that is "40 percent person" would let the text show through faintly, like a ghost behind the shoulder. Remapping 0.3 to 0.7 onto 0 to 1 with a smooth step keeps the edge soft but short.
The model works on a 256-pixel image, so we hand it a copy about 1024 pixels on the long side: big enough to downscale cleanly, small enough to be quick. The mask that comes back is tiny, and it's stretched to the photo's full size when drawn. The browser's smoothing during that stretch is what gives the cut-out its soft edge.
Loading it only when someone asks
MediaPipe's WebAssembly runtime is around 35 MB. Most people using the text tool never tick "Behind subject", so it's loaded the first time someone does, and kept for the rest of the visit:
let segmenter: Promise<ImageSegmenter> | null = null;
function getSegmenter(): Promise<ImageSegmenter> {
if (!segmenter) {
segmenter = (async () => {
const { FilesetResolver, ImageSegmenter } = await import("@mediapipe/tasks-vision");
...
})();
segmenter.catch(() => {
segmenter = null;
});
}
return segmenter;
}Caching the promise rather than the result means two quick clicks share one download. The catch that resets it means a failed download (a dropped connection on a phone) can be retried instead of being cached as a failure forever.
The security policy said no
The site sends a Content-Security-Policy header: a list of the places the browser may load scripts, styles and connections from. Scripts and WebAssembly may only come from our own site. That's a deliberate rule (Part 7), and the usual way to load MediaPipe, from a public CDN, breaks it.
Rather than loosen the policy, we serve the runtime ourselves. A small script runs before every dev and build:
// Copies MediaPipe's WebAssembly runtime ... into public/mediapipe so the browser loads it
// from this site - the Content-Security-Policy only allows scripts and wasm from 'self'.
const from = join(root, "node_modules", "@mediapipe", "tasks-vision", "wasm");
const to = join(root, "public", "mediapipe");
cpSync(from, to, { recursive: true });The copy is git-ignored, because it comes straight from the pinned npm package and there's no reason to store 35 MB twice. The model file is different: it's data, not code, fetched from Google's model storage, which only needed adding to the policy's list of allowed connections.
One consequence we've already met: a checkout whose node_modules doesn't have the package installed fails the TypeScript check on subject.ts. The copy script itself only warns and carries on, so the site still builds without the feature's runtime, but the type-check is a useful early warning that npm ci hasn't been run.
The studio's own fonts
Text on a wedding photo only looks like TheRare in TheRare's fonts. The studio uploads them in Admin, and because using a font on a website means every visitor's browser downloads the file, each upload records a licence note and who confirmed it (migration V129). Customers only see the fonts switched on for them.
The browser can't use a font it hasn't loaded, and drawing text on a canvas with a font that isn't ready silently falls back to a default one. So fonts are registered with the FontFace API and the tool waits for them before drawing:
const face = new FontFace(f.family, await loadFile(f.libraryId));
document.fonts.add(face);
// ...
await document.fonts.load(`${italic ? "italic " : ""}${weight} 48px "${f.family}"`, f.sample || "Aa");Stacking the layers
A text layer stores everything as fractions of the photo, not pixels: size as a fraction of the shorter side, position as fractions of width and height. That's what lets one layer describe both the 1200-pixel preview and the 6000-pixel export.
Drawing "behind" is then four canvas steps:
- The canvas already holds the finished photo with its look applied.
- Make a copy of the photo and keep only the people in it, using the mask with the
destination-inblend mode (keep the copy's pixels only where the mask is solid). - Draw the "behind" text layers onto the main photo.
- Draw the cut-out people back on top, then the normal text layers.
sctx.drawImage(target, 0, 0);
sctx.globalCompositeOperation = "destination-in";
sctx.drawImage(mask, 0, 0, w, h);
behind.forEach((l) => drawLayer(ctx, l, w, h));
ctx.drawImage(subject, 0, 0);There's no clever 3D here. The text really is painted over the whole photo, and then the people are painted back over it.
The same drawText function draws the on-screen preview and the full-size download. That's the most important design choice in the feature: if the preview and the export were drawn by different code, they would drift apart, and someone would download a photo that doesn't match what they saw.
Takeaways
- A model's raw output is rarely what you want to show. A small remap of the mask's edge made the difference between "text ghosting through hair" and a clean cut-out.
- Load heavy features on demand, and cache the promise, not the result.
- Don't weaken a security policy to fit a library. Serve the library from your own origin instead.
- Store positions and sizes relative to the image so one description works at every resolution.
- Draw the preview and the export with the same code. What you see should be exactly what downloads.