Plush Portrait
A cut-out portrait visitors can grab and stretch like a soft toy.
When to use it
- An about page, personal site or founder section where the portrait should feel alive and playful
- A brand mascot or creator profile on a campaign page that invites visitors to play
- Team pages where each person gets a squishable avatar (one live portrait per screen works best)
Watch out
- You supply the images: a transparent PNG or WebP per face, all the same size, square, and pixel-aligned, or the cross-fades will jump. Only faces.rest is required. The install adds a plush-faces agent skill (.claude/skills and .agents/skills) that makes the set with an image tool, checks alignment and converts it
- Images must be same-origin or served with CORS headers; otherwise WebGL cannot read them
- frameBox sets where the circle or square sits in image space; adjust it when the head is not centred like the demo
- The canvas reaches about a third of the portrait's width past each side so skin can stretch. Near a viewport edge, give a parent overflow-x: clip
- Uses WebGL. Keep one per screen, and do not use a real person's photo without their consent
Let your agent add it
One copy holds the install command, when to use it, the props and the design rules. Paste it into Claude Code, Cursor or Codex.
Install with the CLI
Uses the shadcn CLI. The source is copied into your project, so you own every line.
$ npx shadcn@latest add https://sunui.synvize.com/r/plush-portrait.jsonOr install manually
- 1. Install the dependencies.
$ npm install clsx tailwind-merge framer-motion - 2. Add a
cnhelper atlib/utils.tsif you do not have one. Not using shadcn/ui? Also add sunui-theme.css for the colour tokens (how). Then copy the component.plush-portrait.tsx"use client"; import { useEffect, useRef, useState } from "react"; import { useReducedMotion } from "framer-motion"; import { cn } from "@/lib/utils"; /** * PlushPortrait: a cut-out portrait you can grab and stretch like a soft toy. * * The picture is a grid of nodes. Each node stores how far it has been pushed * from home (u) and obeys a damped wave equation with a restoring term: * * ü = c²∇²u − ω²u − γu̇ + ν∇²u̇ * * ∇²u lets a pull drag the skin around it, −ω²u ties the skin back to the * skull, γ settles the wobble and ν∇²u̇ swallows fine ripples first. On top of * that the head leans toward a pull on a slower spring, like a soft neck. * Faces cross-fade on hover, grab, pull and release; the eyes follow the * cursor, blink, and the portrait yawns when the page goes quiet. * * One WebGL draw, no dependencies. Without WebGL, or with reduced motion, it * stays a still picture. */ export const plushFrames = ["circle", "square", "none"] as const; export type PlushFrame = (typeof plushFrames)[number]; /** * Image URLs, all the same size and framing so they can be cross-faded. * Only `rest` is required; a missing face is skipped. */ export type PlushFaces = { rest: string; /** A mouse resting on the face. */ hover?: string; /** The moment it is grabbed, and after a tap or a poke. */ grab?: string; /** Stretched far. */ pull?: string; /** Just let go after a big pull. */ dazed?: string; /** Eyes shut, shown for a moment every few seconds. */ blink?: string; lookLeft?: string; lookRight?: string; /** Played when nobody has touched the page for a while (a yawn). */ idle?: string; }; type FaceKey = keyof PlushFaces; export type PlushPortraitProps = { faces: PlushFaces; alt: string; /** The bust is clipped to this shape and the head pops out above it. */ frame?: PlushFrame; /** Frame position in image space (0 to 1): centre height and half size. */ frameBox?: { y: number; r: number }; /** Classes for the shape behind the bust. Defaults to the primary color. */ backdropClassName?: string; /** Wobble pitch in Hz. Lower is floppier. */ wobble?: number; /** How far a pull spreads, in image widths. */ reach?: number; /** Eyes follow the cursor (needs lookLeft and lookRight). */ follow?: boolean; /** Yawn and blink on their own. */ idle?: boolean; /** Accessible label of the poke button (keyboard and screen readers). */ pokeLabel?: string; className?: string; }; // ---------------------------------------------------------------- tuning const GRID = 36; // cells per side const PAD = 0.32; // empty margin around the image, in image widths const GRAB_R = 0.1; // size of a handful const RUB_R = 0.08; // skin a hovering cursor catches const MAX_PULL = 0.5; // rubber band limit const DAMPING = 0.14; const FLESH = 0.35; // ---------------------------------------------------------------- shaders const VERT = ` attribute vec2 aPos; attribute vec2 aUv; attribute float aShade; attribute float aLift; uniform float uPad; uniform vec2 uPivot; uniform float uTilt; uniform vec2 uShift; varying vec2 vUv; varying vec2 vAt; varying float vShade; void main() { vec2 p = aPos - uPivot; float s = sin(uTilt), c = cos(uTilt); p = vec2(c * p.x - s * p.y, s * p.x + c * p.y) + uPivot + uShift; vec2 q = (p + uPad) / (1.0 + 2.0 * uPad); gl_Position = vec4(q.x * 2.0 - 1.0, 1.0 - q.y * 2.0, -min(aLift * 1.6, 0.99), 1.0); vUv = aUv; vAt = p; vShade = aShade; }`; const FRAG = ` precision mediump float; uniform sampler2D uA; uniform sampler2D uB; uniform float uMix; uniform int uFrame; uniform vec3 uBox; varying vec2 vUv; varying vec2 vAt; varying float vShade; void main() { vec4 col = mix(texture2D(uA, vUv), texture2D(uB, vUv), uMix); float keep = 1.0; // The bust (below the frame's centre) is cut by where it is on screen, not // by where it sits in the picture: the frame stays put when the head leans. if (uFrame > 0 && vUv.y > uBox.y) { float edge; if (uFrame == 1) edge = uBox.z - distance(vAt, uBox.xy); else { // Same 12% corners as the backdrop. float rad = uBox.z * 0.24; vec2 q = abs(vAt - uBox.xy) - (uBox.z - rad); edge = rad - length(max(q, 0.0)) - min(max(q.x, q.y), 0.0); } keep = smoothstep(0.0, 0.004, edge); } if (col.a * keep < 0.004) discard; // empty pixels must not hide what is under them gl_FragColor = vec4(col.rgb * vShade, col.a) * keep; }`; // ---------------------------------------------------------------- engine type Engine = { destroy: () => void; poke: () => void; setFrame: (frame: PlushFrame, box: { y: number; r: number }) => void }; function compile(gl: WebGLRenderingContext, type: number, src: string) { const sh = gl.createShader(type)!; gl.shaderSource(sh, src); gl.compileShader(sh); if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(sh) ?? "shader"); return sh; } function loadImage(src: string) { return new Promise<HTMLImageElement>((resolve, reject) => { const img = new Image(); img.crossOrigin = "anonymous"; img.decoding = "async"; img.onload = () => resolve(img); img.onerror = reject; img.src = src; }); } const smooth = (d: number, r: number) => (d >= r ? 0 : (1 - (d * d) / (r * r)) ** 2); const rand = (a: number, b: number) => a + Math.random() * (b - a); async function createEngine( root: HTMLElement, canvas: HTMLCanvasElement, opts: Required<Pick<PlushPortraitProps, "faces" | "frame" | "frameBox" | "wobble" | "reach" | "follow" | "idle">>, onReady: () => void, onContextLost: () => void, ): Promise<Engine> { const gl = canvas.getContext("webgl", { premultipliedAlpha: true, alpha: true, antialias: true }); if (!gl) throw new Error("no webgl"); const prog = gl.createProgram()!; gl.attachShader(prog, compile(gl, gl.VERTEX_SHADER, VERT)); gl.attachShader(prog, compile(gl, gl.FRAGMENT_SHADER, FRAG)); gl.linkProgram(prog); gl.useProgram(prog); const U = (n: string) => gl.getUniformLocation(prog, n); // Mesh. const n = GRID + 1; const count = n * n; const h = 1 / GRID; const rest = new Float32Array(count * 2); for (let r = 0; r < n; r++) for (let c = 0; c < n; c++) { rest[(r * n + c) * 2] = c * h; rest[(r * n + c) * 2 + 1] = r * h; } const idx = new Uint16Array(GRID * GRID * 6); let k = 0; for (let r = 0; r < GRID; r++) for (let c = 0; c < GRID; c++) { const a = r * n + c, b = a + 1, d = a + n, e = d + 1; idx.set([a, b, d, b, e, d], k); k += 6; } const pos = new Float32Array(rest); const shade = new Float32Array(count).fill(1); const buf = (data: Float32Array, attr: string, size: number, usage: number) => { const b = gl.createBuffer()!; gl.bindBuffer(gl.ARRAY_BUFFER, b); gl.bufferData(gl.ARRAY_BUFFER, data, usage); const loc = gl.getAttribLocation(prog, attr); gl.enableVertexAttribArray(loc); gl.vertexAttribPointer(loc, size, gl.FLOAT, false, 0, 0); return b; }; buf(rest, "aUv", 2, gl.STATIC_DRAW); const posBuf = buf(pos, "aPos", 2, gl.DYNAMIC_DRAW); const shadeBuf = buf(shade, "aShade", 1, gl.DYNAMIC_DRAW); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gl.createBuffer()); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, idx, gl.DYNAMIC_DRAW); // Draw order of the cells, re-sorted while the skin is pulled (see updateMesh). const cells = GRID * GRID; const order = new Uint16Array(cells).map((_, i) => i); const lift = new Float32Array(cells); const drawIdx = new Uint16Array(idx); let reordered = false; gl.uniform1f(U("uPad"), PAD); gl.uniform2f(U("uPivot"), 0.5, 0.85); // The frame is two uniforms: switching it needs no rebuild and no reload. const applyFrame = (frame: PlushFrame, box: { y: number; r: number }) => { gl.useProgram(prog); gl.uniform1i(U("uFrame"), frame === "circle" ? 1 : frame === "square" ? 2 : 0); gl.uniform3f(U("uBox"), 0.5, box.y, box.r); }; applyFrame(opts.frame, opts.frameBox); gl.uniform1i(U("uA"), 0); gl.uniform1i(U("uB"), 1); gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); gl.clearColor(0, 0, 0, 0); // Pulled skin is nearer the viewer: where two patches overlap, depth decides per pixel. gl.enable(gl.DEPTH_TEST); gl.depthFunc(gl.LEQUAL); // Faces. The resting face first; the rest arrive when they arrive. const tex = new Map<FaceKey, WebGLTexture>(); const upload = (img: HTMLImageElement) => { const t = gl.createTexture()!; gl.bindTexture(gl.TEXTURE_2D, t); gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); return t; }; const restImg = await loadImage(opts.faces.rest); tex.set("rest", upload(restImg)); // A coarse alpha map, so only the person (not the empty corners) is grabbable. const HIT = 64; let hitMap: Uint8ClampedArray | null = null; try { const c2 = document.createElement("canvas"); c2.width = c2.height = HIT; const ctx = c2.getContext("2d")!; ctx.drawImage(restImg, 0, 0, HIT, HIT); hitMap = ctx.getImageData(0, 0, HIT, HIT).data; } catch { hitMap = null; // cross-origin image without CORS: everything is grabbable } const onPerson = (x: number, y: number) => { if (x < 0 || y < 0 || x >= 1 || y >= 1) return false; if (!hitMap) return true; return hitMap[(Math.floor(y * HIT) * HIT + Math.floor(x * HIT)) * 4 + 3] > 40; }; let destroyed = false; (Object.keys(opts.faces) as FaceKey[]).forEach((key) => { const src = opts.faces[key]; if (key === "rest" || !src) return; loadImage(src).then((img) => { if (!destroyed) tex.set(key, upload(img)); }, () => {}); }); // Physics state. const ux = new Float32Array(count), uy = new Float32Array(count); const vx = new Float32Array(count), vy = new Float32Array(count); const lx = new Float32Array(count), ly = new Float32Array(count); const grabW = new Float32Array(count); const grabUx = new Float32Array(count), grabUy = new Float32Array(count); const height = new Float32Array(count); const liftBuf = buf(height, "aLift", 1, gl.DYNAMIC_DRAW); const omega = 2 * Math.PI * opts.wobble; const c2 = (opts.reach * omega) ** 2; const w2 = omega * omega; const gamma = 2 * DAMPING * omega; const nu = FLESH * 0.03; const invH2 = 1 / (h * h); let tilt = 0, tiltV = 0, shiftX = 0, shiftV = 0; const laplace = (f: Float32Array, out: Float32Array) => { for (let r = 0; r < n; r++) for (let c = 0; c < n; c++) { const i = r * n + c, v = f[i]; const L = c > 0 ? f[i - 1] : v, R = c < GRID ? f[i + 1] : v; const T = r > 0 ? f[i - n] : v, B = r < GRID ? f[i + n] : v; out[i] = (L + R + T + B - 4 * v) * invH2; } }; const lvx = new Float32Array(count), lvy = new Float32Array(count); // Pointer state, in image space (0 to 1 over the picture). const hand = { down: false, id: -1, sx: 0, sy: 0, x: 0, y: 0, px: 0, py: 0, vx: 0, vy: 0, pulled: 0 }; const hover = { on: false, since: 0, x: 0, y: 0 }; let pointer: { x: number; y: number } | null = null; let lastActive = performance.now(); let pulls = 0; // The box is measured once and again only after a scroll or resize, so a // pointer move never forces a layout. let rect = root.getBoundingClientRect(), rectStale = false; const toImage = (e: PointerEvent) => { if (rectStale) { rect = root.getBoundingClientRect(); rectStale = false; } return { x: (e.clientX - rect.left) / rect.width, y: (e.clientY - rect.top) / rect.height }; }; const onScroll = () => { rectStale = true; }; let gaze = 0; // -1 left, 0 ahead, 1 right const nodeAt = (i: number) => [rest[i * 2] + ux[i], rest[i * 2 + 1] + uy[i]] as const; const impulse = (x: number, y: number, dx: number, dy: number, radius: number) => { for (let i = 0; i < count; i++) { const [px, py] = nodeAt(i); const w = smooth(Math.hypot(px - x, py - y), radius); if (w) { vx[i] += dx * w; vy[i] += dy * w; } } wake(); }; // Faces and timing. let faceA: FaceKey = "rest", faceB: FaceKey = "rest", mixT = 1, fadeMs = 90; let flash: { face: FaceKey; until: number } | null = null; let dazedUntil = 0; let nextBlink = performance.now() + rand(2500, 5000), blinkUntil = 0; let nextIdle = performance.now() + rand(9000, 14000), idleUntil = 0; const has = (f: FaceKey) => tex.has(f); const want = (now: number): [FaceKey, number] => { if (flash && now < flash.until && has(flash.face)) return [flash.face, 60]; if (hand.down) return [hand.pulled > 0.12 && has("pull") ? "pull" : has("grab") ? "grab" : "rest", 70]; if (now < dazedUntil && has("dazed")) return ["dazed", 90]; if (hover.on && now - hover.since > 350 && has("hover")) return ["hover", 120]; if (now < idleUntil && has("idle")) return ["idle", 220]; if (opts.idle && now < blinkUntil && has("blink")) return ["blink", 40]; if (opts.follow && pointer && !hover.on) { const dx = pointer.x - 0.5; if (dx < -0.65 && has("lookLeft")) return ["lookLeft", 110]; if (dx > 0.65 && has("lookRight")) return ["lookRight", 110]; } return ["rest", 110]; }; const showFace = (face: FaceKey, ms: number) => { if (face === faceB) return; faceA = mixT > 0.5 ? faceB : faceA; faceB = face; mixT = 0; fadeMs = ms; }; // Loop. // The loop only runs while something moves: the skin, a fade, a hand. At // rest it sleeps and a timer wakes it for the next blink or yawn. let raf = 0, timer = 0, running = false, onScreen = true, pageShown = document.visibilityState === "visible"; let energy = 1, last = performance.now(), dirty = true; const visible = () => onScreen && pageShown; const kick = () => { dirty = true; clearTimeout(timer); if (!running && visible() && !destroyed) { running = true; last = performance.now(); raf = requestAnimationFrame(tick); } }; const wake = () => { energy = 1; kick(); }; const SLEEP = 2e-5; const nextClock = (now: number) => { const times = [blinkUntil, idleUntil, dazedUntil, flash ? flash.until : 0]; if (hover.on) times.push(hover.since + 360); if (opts.idle) times.push(nextBlink, Math.max(nextIdle, lastActive + 9000)); let soon = Infinity; for (const t of times) if (t > now && t < soon) soon = t; return soon; }; const step = (dt: number) => { laplace(ux, lx); laplace(uy, ly); laplace(vx, lvx); laplace(vy, lvy); for (let i = 0; i < count; i++) { vx[i] += (c2 * lx[i] - w2 * ux[i] - gamma * vx[i] + nu * lvx[i]) * dt; vy[i] += (c2 * ly[i] - w2 * uy[i] - gamma * vy[i] + nu * lvy[i]) * dt; ux[i] += vx[i] * dt; uy[i] += vy[i] * dt; } if (hand.down) { let dx = hand.x - hand.sx, dy = hand.y - hand.sy; const d = Math.hypot(dx, dy); if (d > 0) { const s = (MAX_PULL * Math.tanh(d / MAX_PULL)) / d; // rubber band dx *= s; dy *= s; } hand.pulled = Math.hypot(dx, dy); for (let i = 0; i < count; i++) { const w = grabW[i]; if (!w) continue; const tx = grabUx[i] + dx, ty = grabUy[i] + dy; ux[i] += (tx - ux[i]) * w; uy[i] += (ty - uy[i]) * w; vx[i] += (hand.vx - vx[i]) * w; vy[i] += (hand.vy - vy[i]) * w; } } // The soft neck. const targetTilt = hand.down ? Math.max(-0.14, Math.min(0.14, (hand.x - hand.sx) * 0.45)) : 0; const targetShift = hand.down ? (hand.x - hand.sx) * 0.05 : 0; const ws = 2 * Math.PI * 1.3; tiltV += (ws * ws * (targetTilt - tilt) - 2 * 0.22 * ws * tiltV) * dt; tilt += tiltV * dt; shiftV += (ws * ws * (targetShift - shiftX) - 2 * 0.3 * ws * shiftV) * dt; shiftX += shiftV * dt; }; const updateMesh = () => { // Pulled skin lifts toward the viewer, bunched skin ridges up; the slope // of that height field fakes the light. for (let r = 0; r < n; r++) for (let c = 0; c < n; c++) { const i = r * n + c; const L = c > 0 ? i - 1 : i, R = c < GRID ? i + 1 : i, T = r > 0 ? i - n : i, B = r < GRID ? i + n : i; const div = (ux[R] - ux[L] + uy[B] - uy[T]) / (2 * h); height[i] = Math.hypot(ux[i], uy[i]) * 0.9 + Math.max(0, -div) * 0.02; pos[i * 2] = rest[i * 2] + ux[i]; pos[i * 2 + 1] = rest[i * 2 + 1] + uy[i]; } for (let r = 0; r < n; r++) for (let c = 0; c < n; c++) { const i = r * n + c; const L = c > 0 ? i - 1 : i, R = c < GRID ? i + 1 : i, T = r > 0 ? i - n : i, B = r < GRID ? i + n : i; const gx = (height[R] - height[L]) / (2 * h), gy = (height[B] - height[T]) / (2 * h); shade[i] = Math.max(0.78, Math.min(1.22, 1 + height[i] * 0.25 - (gx * 0.5 + gy * 0.7) * 0.06)); } // The farther a patch is pulled, the later it is drawn, so a pinched cheek // lands on top of what it crosses instead of under it. The sort keeps soft // edges blending over what is behind them; depth tidies the seam. let lifted = false; for (let r = 0; r < GRID; r++) for (let c = 0; c < GRID; c++) { const a = r * n + c; const v = height[a] + height[a + 1] + height[a + n] + height[a + n + 1]; lift[r * GRID + c] = v; if (v > 0.004) lifted = true; } if (lifted || reordered) { if (lifted) order.sort((p, q) => lift[p] - lift[q] || p - q); else for (let j = 0; j < cells; j++) order[j] = j; for (let j = 0; j < cells; j++) drawIdx.set(idx.subarray(order[j] * 6, order[j] * 6 + 6), j * 6); gl.bufferSubData(gl.ELEMENT_ARRAY_BUFFER, 0, drawIdx); reordered = lifted; } gl.bindBuffer(gl.ARRAY_BUFFER, posBuf); gl.bufferSubData(gl.ARRAY_BUFFER, 0, pos); gl.bindBuffer(gl.ARRAY_BUFFER, shadeBuf); gl.bufferSubData(gl.ARRAY_BUFFER, 0, shade); gl.bindBuffer(gl.ARRAY_BUFFER, liftBuf); gl.bufferSubData(gl.ARRAY_BUFFER, 0, height); }; const resize = () => { const rect = canvas.getBoundingClientRect(); const dpr = Math.min(window.devicePixelRatio || 1, 2); const size = Math.max(1, Math.round(rect.width * dpr)); if (canvas.width !== size) { canvas.width = canvas.height = size; dirty = true; } gl.viewport(0, 0, canvas.width, canvas.height); wake(); }; const draw = () => { gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, tex.get(faceA) ?? tex.get("rest")!); gl.activeTexture(gl.TEXTURE1); gl.bindTexture(gl.TEXTURE_2D, tex.get(faceB) ?? tex.get("rest")!); gl.uniform1f(U("uMix"), mixT); gl.uniform1f(U("uTilt"), tilt); gl.uniform2f(U("uShift"), shiftX, 0); gl.drawElements(gl.TRIANGLES, idx.length, gl.UNSIGNED_SHORT, 0); }; function tick(now: number) { if (destroyed) return; const dt = Math.min(0.05, (now - last) / 1000); last = now; // Clocks: blinking and idling. if (opts.idle) { if (now > nextBlink) { blinkUntil = now + 130; nextBlink = now + rand(2600, 5600); } if (now - lastActive > 9000 && now > nextIdle && !hover.on) { idleUntil = now + 1700; nextIdle = now + rand(11000, 17000); impulse(0.5, 0.55, 0, -0.25, 0.3); } } const [face, ms] = want(now); showFace(face, ms); if (mixT < 1) { mixT = Math.min(1, mixT + (dt * 1000) / fadeMs); dirty = true; } if (energy > SLEEP || hand.down) { // Short steps keep the stiffest ripple stable, however slow the frame was. const sub = Math.max(4, Math.ceil(dt / 0.004)); for (let s = 0; s < sub; s++) step(dt / sub); let e = 0; for (let i = 0; i < count; i++) e += Math.abs(ux[i]) + Math.abs(uy[i]) + Math.abs(vx[i]) * 0.1 + Math.abs(vy[i]) * 0.1; energy = e / count + Math.abs(tilt) + Math.abs(tiltV) * 0.1 + Math.abs(shiftX); if (energy <= SLEEP && !hand.down) { // Settled: put every node exactly home so the next frame is the plain picture. ux.fill(0); uy.fill(0); vx.fill(0); vy.fill(0); tilt = tiltV = shiftX = shiftV = 0; } updateMesh(); dirty = true; } if (dirty) { draw(); dirty = false; } if (visible() && (energy > SLEEP || hand.down || mixT < 1)) { raf = requestAnimationFrame(tick); return; } running = false; if (!visible()) return; const soon = nextClock(now); if (soon < Infinity) timer = window.setTimeout(kick, Math.max(16, soon - now)); } // Events. const onDown = (e: PointerEvent) => { const p = toImage(e); if (!onPerson(p.x, p.y) || (e.target as Element).closest("button")) return; lastActive = performance.now(); if (e.pointerType === "touch") { // Fingers share the screen with scrolling: a tap prods, a sideways drag grabs. impulse(p.x, p.y, 0, 0.6, GRAB_R); } e.preventDefault(); try { root.setPointerCapture(e.pointerId); } catch { /* moves still arrive on window */ } hand.down = true; hand.id = e.pointerId; hand.sx = hand.x = hand.px = p.x; hand.sy = hand.y = hand.py = p.y; hand.vx = hand.vy = hand.pulled = 0; for (let i = 0; i < count; i++) { const [px, py] = nodeAt(i); grabW[i] = smooth(Math.hypot(px - p.x, py - p.y), GRAB_R); grabUx[i] = ux[i]; grabUy[i] = uy[i]; } wake(); }; const onMove = (e: PointerEvent) => { const p = toImage(e); pointer = p; if (hand.down && e.pointerId === hand.id) { const now = performance.now(); hand.vx = (p.x - hand.px) * 60; hand.vy = (p.y - hand.py) * 60; hand.px = hand.x = p.x; hand.py = hand.y = p.y; lastActive = now; wake(); return; } if (e.pointerType !== "mouse") return; if (opts.follow) { // Only a change of direction needs a frame. const dx = p.x - 0.5, g = dx < -0.65 ? -1 : dx > 0.65 ? 1 : 0; if (g !== gaze) { gaze = g; kick(); } } const over = onPerson(p.x, p.y); if (over && !hover.on) hover.since = performance.now(); if (over) { // A hovering cursor already has half a hold of the skin. const dx = p.x - hover.x, dy = p.y - hover.y; if (hover.on && Math.hypot(dx, dy) < 0.08) { for (let i = 0; i < count; i++) { const [px, py] = nodeAt(i); const w = smooth(Math.hypot(px - p.x, py - p.y), RUB_R); if (w) { ux[i] += dx * w * 0.35; uy[i] += dy * w * 0.35; } } } lastActive = performance.now(); wake(); } if (hover.on && !over) kick(); hover.on = over; hover.x = p.x; hover.y = p.y; }; const onUp = (e: PointerEvent) => { if (!hand.down || e.pointerId !== hand.id) return; hand.down = false; const now = performance.now(); if (hand.pulled > 0.15) { pulls++; dazedUntil = now + (pulls >= 3 ? 1800 : 1100); } else { flash = { face: "grab", until: now + 380 }; pulls = Math.max(0, pulls - 1); } lastActive = now; wake(); }; const onLeave = () => { if (hover.on) { hover.on = false; kick(); } }; // Listen on the portrait, not the canvas: the canvas is larger than the // picture and must not swallow clicks meant for whatever sits beside it. root.addEventListener("pointerdown", onDown); window.addEventListener("pointermove", onMove, { passive: true }); window.addEventListener("pointerup", onUp); window.addEventListener("pointercancel", onUp); root.addEventListener("pointerleave", onLeave); window.addEventListener("scroll", onScroll, { passive: true, capture: true }); const ro = new ResizeObserver(() => { rectStale = true; resize(); }); ro.observe(canvas); const io = new IntersectionObserver(([entry]) => { onScreen = entry.isIntersecting; if (visible()) kick(); }); io.observe(root); const onVis = () => { pageShown = document.visibilityState === "visible"; if (visible()) kick(); }; document.addEventListener("visibilitychange", onVis); // Phones take WebGL away when they need the memory: fall back to the picture. const onLost = (e: Event) => { e.preventDefault(); destroyed = true; cancelAnimationFrame(raf); clearTimeout(timer); onContextLost(); }; canvas.addEventListener("webglcontextlost", onLost); resize(); updateMesh(); draw(); onReady(); return { setFrame: (frame, box) => { if (!destroyed) { applyFrame(frame, box); kick(); } }, poke: () => { const now = performance.now(); flash = { face: "grab", until: now + 500 }; lastActive = now; impulse(0.5, 0.42, rand(-0.6, 0.6), 0.9, 0.16); }, destroy: () => { destroyed = true; cancelAnimationFrame(raf); clearTimeout(timer); ro.disconnect(); io.disconnect(); root.removeEventListener("pointerdown", onDown); window.removeEventListener("pointermove", onMove); window.removeEventListener("pointerup", onUp); window.removeEventListener("pointercancel", onUp); root.removeEventListener("pointerleave", onLeave); window.removeEventListener("scroll", onScroll, { capture: true }); document.removeEventListener("visibilitychange", onVis); canvas.removeEventListener("webglcontextlost", onLost); gl.getExtension("WEBGL_lose_context")?.loseContext(); }, }; } // ---------------------------------------------------------------- component export function PlushPortrait({ faces, alt, frame = "circle", frameBox = { y: 0.58, r: 0.42 }, backdropClassName = "bg-primary", wobble = 2.3, reach = 0.085, follow = true, idle = true, pokeLabel = "Poke", className, }: PlushPortraitProps) { const rootRef = useRef<HTMLDivElement>(null); const canvasRef = useRef<HTMLCanvasElement>(null); const engineRef = useRef<Engine | null>(null); const [live, setLive] = useState(false); const reduced = useReducedMotion(); const facesKey = JSON.stringify(faces); const boxKey = `${frameBox.y},${frameBox.r}`; // A rebuilt engine needs a fresh canvas: the old one's WebGL context is released on destroy. const engineKey = [facesKey, wobble, reach, follow, idle].join("|"); const frameRef = useRef({ frame, frameBox }); frameRef.current = { frame, frameBox }; useEffect(() => { const root = rootRef.current, canvas = canvasRef.current; if (!root || !canvas || reduced) return; let cancelled = false; // Nothing is downloaded until the portrait is about to come into view. const io = new IntersectionObserver(([entry]) => { if (!entry.isIntersecting) return; io.disconnect(); createEngine( root, canvas, { faces, ...frameRef.current, wobble, reach, follow, idle }, () => { if (!cancelled) setLive(true); }, () => { engineRef.current = null; if (!cancelled) setLive(false); }, ).then( (engine) => { if (cancelled) engine.destroy(); else engineRef.current = engine; }, () => { /* No WebGL: the picture stays. */ }, ); }, { rootMargin: "300px" }); io.observe(root); return () => { cancelled = true; io.disconnect(); engineRef.current?.destroy(); engineRef.current = null; setLive(false); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [engineKey, reduced]); useEffect(() => { engineRef.current?.setFrame(frame, frameBox); // eslint-disable-next-line react-hooks/exhaustive-deps }, [frame, boxKey]); const { y, r } = frameBox; // The still picture gets the same clip as the shader: inside the shape, or above its centre. const mask = frame === "none" ? undefined : `${frame === "circle" ? `radial-gradient(${r * 100}% ${r * 100}% at 50% ${y * 100}%, #000 99.5%, transparent 100%)` : `linear-gradient(#000, #000) ${(0.5 - r) * 100}% ${(y - r) * 100}% / ${r * 200}% ${r * 200}% no-repeat` }, linear-gradient(#000 ${y * 100}%, transparent ${y * 100}%)`; return ( <div ref={rootRef} className={cn("relative aspect-square w-full select-none", live && "cursor-grab touch-pan-y active:cursor-grabbing", className)}> {frame !== "none" && ( <div aria-hidden className={cn("absolute", frame === "circle" ? "rounded-full" : "rounded-[12%]", backdropClassName)} style={{ left: `${(0.5 - r) * 100}%`, top: `${(y - r) * 100}%`, width: `${r * 200}%`, height: `${r * 200}%` }} /> )} <img src={faces.rest} alt={alt} draggable={false} className={cn("absolute inset-0 size-full transition-opacity duration-300", live && "opacity-0")} style={mask ? { maskImage: mask, WebkitMaskImage: mask } : undefined} /> {!reduced && ( <canvas key={engineKey} ref={canvasRef} aria-hidden className={cn("pointer-events-none absolute", !live && "invisible")} style={{ inset: `${-PAD * 100}%`, width: `${(1 + 2 * PAD) * 100}%`, height: `${(1 + 2 * PAD) * 100}%` }} /> )} {live && ( <button type="button" onClick={() => engineRef.current?.poke()} className="absolute left-1/2 top-[30%] size-[30%] -translate-x-1/2 rounded-full opacity-0 focus-visible:opacity-100 focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-ring pointer-events-none focus-visible:pointer-events-auto" aria-label={pokeLabel} /> )} </div> ); }.claude/skills/plush-faces/SKILL.md--- name: plush-faces description: Make the face images for the SunUI PlushPortrait block (a cut-out portrait visitors can grab and stretch). Use when the user has installed plush-portrait, asks for its faces, expressions or images, wants their own photo or a character in it, or the cross-fades between faces jump. Covers consent, the face list and image spec, generating the set with an image tool (or handing the user prompts), checking alignment, converting to WebP and wiring up the faces prop. --- # PlushPortrait face set PlushPortrait needs one image per expression. They are cross-faded while the skin stretches, so they must be **the same picture with only the face changed**: same size, same framing, same head position to the pixel. Only `rest` is required; any missing face is skipped. ## 1. Who is in the picture Ask before making anything: - **The user themself**: ask for one sharp, front-facing photo (head and shoulders, even light, plain background). - **A fictional character**: ask for a short description (age, hair, clothing color, style: photo or illustration). Prefer this when the user is unsure. - **Someone else**: only with that person's consent. Never make a set of a celebrity, public figure or anyone who has not agreed, even "as a joke". Say why and offer a fictional character instead. ## 2. The faces | key | file | expression | when it shows | |---|---|---|---| | `rest` | `rest.png` | gentle closed-mouth smile, eyes on the viewer | always (required) | | `grab` | `grab.png` | shocked: brows high, eyes wide, small round open mouth | grabbed, tapped, poked | | `pull` | `pull.png` | ouch: eyes squeezed shut, nose wrinkled, clenched teeth | stretched far | | `blink` | `blink.png` | rest with both eyes closed | every few seconds | | `hover` | `hover.png` | mildly annoyed: brows down, lips pursed to one side | mouse resting on the face | | `dazed` | `dazed.png` | dizzy: half-lidded eyes looking different ways, lopsided smile | just let go after a big pull | | `idle` | `idle.png` | big yawn, mouth wide open, eyes nearly shut | page quiet for a while | | `lookLeft` | `look-left.png` | rest, irises shifted to the image's left edge | cursor far to the left | | `lookRight` | `look-right.png` | rest, irises shifted to the image's right edge | cursor far to the right | If the user wants fewer images, the minimum that still feels alive is `rest`, `grab`, `pull`, `blink`. The tone of each face is the user's choice (a brand mascot may want "pleased" instead of "annoyed" on hover); keep the keys. ## 3. Image spec - Square, 1024 x 1024 or larger, PNG or WebP with a **transparent** background. - Head and shoulders, facing the camera, head centred horizontally. - Top of the head about 8% below the top edge, shoulders cut off by the bottom edge. The head pops out above the frame, so it needs that room. - Soft even light, no shadow on the background, no text, no props crossing the face. - Every face identical to `rest` except the expression: same hair strands, clothing, light, colors, crop. ## 4. Making the set The one rule that matters: **make `rest` first, then make every other face as an edit of `rest`.** Never generate faces independently; each new generation moves the head and changes the person. ### A. You have an image tool (gpt-image, Codex, Gemini, Flux, etc.) 1. **rest.** From the user's photo: cut out the background and reframe to the spec (or edit it into the spec with the tool). From a description, generate it: > A square 1024x1024 PNG with a fully transparent background: a friendly [photorealistic studio portrait / flat illustration] of [description], wearing [plain top in one color]. Head and shoulders bust, facing the camera straight on, head perfectly centred horizontally, eyes looking directly at the viewer, gentle closed-mouth smile. The top of the head sits about 8% below the top edge; shoulders are cut off by the bottom edge. Soft even studio lighting, sharp focus, no props, no text, no shadow on the background. Show `rest` to the user and get a yes before making the others. 2. **Each other face**, with `rest.png` as the input image (edit mode, not text-to-image): > Edit this image. Keep EVERYTHING identical: same person and identity, same hair, same clothing, same lighting, and above all the exact same head size, head position, framing and camera, pixel-aligned so the images can be cross-faded. Keep the transparent background. Change ONLY the facial expression: [expression from the table]. Faces are independent edits of `rest`, so they can be made in parallel. Save each under the file name in the table. ### B. You have no image tool Give the user the two prompts above filled in for their case, the file names, and the order (rest first, then each face as an edit of rest in ChatGPT, Gemini or similar). Ask them to put the files in one folder and tell you where; then continue at step 5. ### C. The user wants to shoot real photos Tripod at head height, same distance, same light, camera on a timer, one photo per expression without moving the chair. Cut out the backgrounds with the same tool for every photo. Expect some drift; the check below shows which ones to retake. ## 5. Check and convert Run the checker that comes with this skill (`check-faces.mjs`, next to this file) on the folder: ```bash node .claude/skills/plush-faces/check-faces.mjs <folder> ``` (Use `.agents/skills/plush-faces/...` if that is where it was installed. It needs `sharp`; Next.js projects usually have it, otherwise `npm i -D sharp`.) It compares every face's silhouette with `rest`: - **ok**: under 4% of the silhouette differs and the person moved less than 0.8% of the width. Hair-edge differences of 2 to 3% are normal. - **warn**: visible as a small hop on the cross-fade. Regenerate if the user cares. - **FAIL**: will visibly jump, or the size or transparency is wrong. Regenerate that face as an edit of `rest`. It also prints a suggested `frameBox` from where the top of the head is. When everything passes, convert into the app's `public` folder (768px WebP, about 60 KB each): ```bash node .claude/skills/plush-faces/check-faces.mjs <folder> --out public/plush/<name> ``` It prints the `faces` object to paste. ## 6. Wire it up ```tsx import { PlushPortrait, type PlushFaces } from "@/components/plush-portrait"; const faces: PlushFaces = { rest: "/plush/mei/rest.webp", grab: "/plush/mei/grab.webp", // ...the rest the checker printed }; <PlushPortrait faces={faces} alt="Portrait of Mei, smiling" pokeLabel="Poke Mei" frame="circle" frameBox={{ y: 0.58, r: 0.42 }} /> ``` Use the import path the shadcn CLI printed. Write `alt` and `pokeLabel` in the page's language. Use the suggested `frameBox`, then look at it: the circle should hold the shoulders and the head should rise above it. ## Troubleshooting - **A face jumps on the cross-fade**: it was generated, not edited, or the tool recropped it. Rerun the checker and regenerate the failing faces from `rest`. - **Colors shift between faces**: say "same white balance and exposure as the input" in the edit prompt, or regenerate. - **Stays a still picture**: images on another domain need CORS headers (WebGL cannot read them otherwise). Serve them from `public` or the same origin. - **Grey or white box around the person**: the background is not transparent. Cut it out again. - **The head is cut by the frame**: there is no room above the head in `rest`. Regenerate `rest` with more space on top, then the other faces from it..claude/skills/plush-faces/check-faces.mjs#!/usr/bin/env node /* global process, console */ // Checks a PlushPortrait face set and, with --out, converts it for the web. // // node check-faces.mjs <folder> check only // node check-faces.mjs <folder> --out public/plush/mei [--size 768] // // The folder holds one image per face, named after the face (rest.png, // grab.webp, look-left.png ...). Needs sharp, which Next.js projects // usually have; otherwise: npm i -D sharp // // Exit code 1 when a face would visibly jump during a cross-fade. import fs from "node:fs"; import path from "node:path"; const FACES = [ ["rest", "rest"], ["hover", "hover"], ["grab", "grab"], ["pull", "pull"], ["dazed", "dazed"], ["blink", "blink"], ["idle", "idle"], ["lookLeft", "look-left"], ["lookRight", "look-right"], ]; const EXT = [".png", ".webp", ".jpg", ".jpeg"]; const GRID = 256; // silhouettes are compared at this size const WARN = 4; // % of the silhouette that may differ before we warn const FAIL = 8; // ... and before we fail const args = process.argv.slice(2); const dir = args.find((a) => !a.startsWith("--")); const flag = (name) => { const i = args.indexOf(name); return i >= 0 ? args[i + 1] : undefined; }; const out = flag("--out"); const size = Number(flag("--size") ?? 768); if (!dir) { console.error("Usage: node check-faces.mjs <folder> [--out <folder>] [--size 768]"); process.exit(2); } let sharp; try { sharp = (await import("sharp")).default; } catch { console.error("sharp is not installed. Run: npm i -D sharp"); process.exit(2); } const find = (base) => { for (const ext of EXT) { const file = path.join(dir, base + ext); if (fs.existsSync(file)) return file; } return null; }; async function silhouette(file) { const { data } = await sharp(file) .ensureAlpha() .resize(GRID, GRID, { fit: "fill" }) .extractChannel("alpha") .raw() .toBuffer({ resolveWithObject: true }); return data; } function compare(a, b) { let union = 0, diff = 0, ax = 0, ay = 0, an = 0, bx = 0, by = 0, bn = 0; for (let i = 0; i < a.length; i++) { const A = a[i] > 128, B = b[i] > 128; if (A || B) union++; if (A !== B) diff++; const x = i % GRID, y = (i / GRID) | 0; if (A) { ax += x; ay += y; an++; } if (B) { bx += x; by += y; bn++; } } const shift = an && bn ? Math.hypot(ax / an - bx / bn, ay / an - by / bn) / GRID : 1; return { mismatch: union ? (diff / union) * 100 : 100, shift: shift * 100 }; } function topRow(alpha) { for (let y = 0; y < GRID; y++) for (let x = 0; x < GRID; x++) if (alpha[y * GRID + x] > 128) return y / GRID; return 0; } const restFile = find("rest"); if (!restFile) { console.error(`No rest image in ${dir}. rest.png (or .webp/.jpg) is the one face that is required.`); process.exit(1); } const restMeta = await sharp(restFile).metadata(); const restAlpha = await silhouette(restFile); const problems = []; const found = []; console.log(`\nFace set in ${dir}\n`); console.log("face file size silhouette shift verdict"); for (const [key, base] of FACES) { const file = find(base); if (!file) { console.log(`${key.padEnd(11)} (missing, skipped by the component)`); continue; } const meta = await sharp(file).metadata(); const notes = []; if (meta.width !== meta.height) notes.push("not square"); if (meta.width !== restMeta.width || meta.height !== restMeta.height) notes.push(`size differs from rest (${restMeta.width}x${restMeta.height})`); if (!meta.hasAlpha) notes.push("no transparency: cut the background out"); if (meta.width < 768) notes.push("smaller than 768px, will look soft"); // The top corners should be empty (the shoulders may fill the bottom ones): // a background that is white rather than transparent fails here. const alpha = await silhouette(file); if (meta.hasAlpha && (alpha[0] > 128 || alpha[GRID - 1] > 128)) notes.push("top corners are not transparent"); const { mismatch, shift } = key === "rest" ? { mismatch: 0, shift: 0 } : compare(restAlpha, alpha); let verdict = "ok"; if (mismatch > FAIL || shift > 1.5) verdict = "FAIL"; else if (mismatch > WARN || shift > 0.8) verdict = "warn"; if (notes.some((n) => n.startsWith("size") || n.startsWith("no transparency"))) verdict = "FAIL"; if (verdict !== "ok") problems.push({ key, verdict, mismatch, shift, notes }); console.log( `${key.padEnd(11)} ${path.basename(file).padEnd(20)} ${`${meta.width}x${meta.height}`.padEnd(11)} ${`${mismatch.toFixed(1)}%`.padEnd(11)} ${`${shift.toFixed(2)}%`.padEnd(7)} ${verdict}${notes.length ? ` (${notes.join("; ")})` : ""}`, ); found.push({ key, base, file }); } // Where the circle should sit: the default frameBox assumes the top of the // head is 8% below the top edge. const top = topRow(restAlpha); const y = Math.min(0.64, Math.max(0.5, top + 0.5)); console.log(`\nTop of head at ${(top * 100).toFixed(0)}% of the height. Suggested frameBox: { y: ${y.toFixed(2)}, r: 0.42 }`); if (top < 0.03) console.log("The head touches the top edge: there is no room for it to pop out of the frame. Leave about 8% above it."); if (problems.length) { console.log("\nFix before shipping:"); for (const p of problems) { const why = []; if (p.mismatch > WARN) why.push(`${p.mismatch.toFixed(1)}% of the silhouette differs from rest`); if (p.shift > 0.8) why.push(`the person moved by ${p.shift.toFixed(2)}% of the width`); console.log(`- ${p.key} (${p.verdict}): ${[...why, ...p.notes].join("; ")}. Regenerate it as an edit of rest, not from scratch.`); } } else { console.log("\nAll faces line up with rest."); } if (out) { fs.mkdirSync(out, { recursive: true }); for (const f of found) { await sharp(f.file).ensureAlpha().resize(size, size, { fit: "fill" }).webp({ quality: 86, effort: 6 }).toFile(path.join(out, `${f.base}.webp`)); } const publicPath = "/" + path.relative(path.join(process.cwd(), "public"), out).split(path.sep).join("/"); const web = out.includes(`public${path.sep}`) || out.startsWith("public") ? publicPath : out; console.log(`\nWrote ${found.length} WebP files (${size}px) to ${out}\n`); console.log("const faces: PlushFaces = {"); for (const f of found) console.log(` ${f.key}: "${web}/${f.base}.webp",`); console.log("};"); } process.exit(problems.some((p) => p.verdict === "FAIL") ? 1 : 0);





