{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"thick-glass-pill-button-that-refracts-a-portrait-and-flattens-when-pressed","type":"registry:component","title":"Thick Glass Pill Button That Refracts a Portrait and Flattens When Pressed","description":"Glass pill button on a canvas: its rounded rim bends the portrait behind it with colour fringing and flattens when pressed. Free React and HTML to copy.","dependencies":[],"files":[{"path":"components/we-inc/thick-glass-pill-button-that-refracts-a-portrait-and-flattens-when-pressed.tsx","type":"registry:component","content":"import { useEffect, useRef, useState } from \"react\";\n\n// Everything a visitor is likely to change sits here.\nconst LABEL = \"Book a fitting\";\nconst CAPTION = \"Press it. The glass flattens, then rings.\";\nconst PHOTO = \"https://images.pexels.com/photos/39325164/pexels-photo-39325164.jpeg?auto=compress&cs=tinysrgb&w=1000\";\nconst PHOTO_ALT = \"Woman in an orange halter top and lime skirt seated against a deep orange studio backdrop\";\nconst FOCUS = { x: 0.5, y: 1 }; // which part of the photo stays in frame\nconst BEND = 36; // how far the rim bends the picture, in pixels\nconst SMOKE = 0.8; // 1 is clear glass, lower is darker\nconst RES = 2; // canvas pixels per CSS pixel\n\nexport default function ThickGlassPillButton() {\n  const card = useRef<HTMLDivElement>(null);\n  const photo = useRef<HTMLImageElement>(null);\n  const button = useRef<HTMLButtonElement>(null);\n  const squash = useRef<HTMLSpanElement>(null);\n  const shadow = useRef<HTMLSpanElement>(null);\n  const canvas = useRef<HTMLCanvasElement>(null);\n  const [live, setLive] = useState(false);\n  const [count, setCount] = useState(0);\n\n  useEffect(() => {\n    const cardEl = card.current, img = photo.current, btn = button.current, cv = canvas.current, sq = squash.current, sh = shadow.current;\n    if (!cardEl || !img || !btn || !cv || !sq || !sh) return;\n    const ctx = cv.getContext(\"2d\");\n    const bg = document.createElement(\"canvas\");\n    const bgx = bg.getContext(\"2d\", { willReadFrequently: true });\n    if (!ctx || !bgx) return;\n    const reduce = window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n\n    let W = 0, H = 0, PAD = 0, bgW = 0, bgH = 0;\n    let box = { bx: 0, by: 0, bw: 0, bh: 0, cw: 0, ch: 0 };\n    let alpha = new Float32Array(0), gx = new Float32Array(0), gy = new Float32Array(0), rim = new Float32Array(0), bend = new Float32Array(0), gloss = new Float32Array(0);\n    let out: ImageData | null = null;\n    let broken = false;\n\n    // One pass over the pill: how far each pixel is from the edge and which way the edge faces.\n    const measure = () => {\n      const c = cardEl.getBoundingClientRect(), b = btn.getBoundingClientRect();\n      if (!b.width || !c.width) return;\n      box = { bx: b.left - c.left, by: b.top - c.top, bw: b.width, bh: b.height, cw: c.width, ch: c.height };\n      W = Math.round(b.width * RES); H = Math.round(b.height * RES);\n      PAD = Math.round((BEND + 10) * RES);\n      bgW = W + PAD * 2; bgH = H + PAD * 2;\n      cv.width = W; cv.height = H; bg.width = bgW; bg.height = bgH;\n      const n = W * H;\n      alpha = new Float32Array(n); gx = new Float32Array(n); gy = new Float32Array(n); rim = new Float32Array(n); bend = new Float32Array(n); gloss = new Float32Array(n);\n      out = ctx.createImageData(W, H);\n      const r = H / 2, half = W / 2 - r, bevel = r * 0.58;\n      for (let y = 0; y < H; y++) {\n        for (let x = 0; x < W; x++) {\n          const px = x + 0.5 - W / 2, py = y + 0.5 - H / 2;\n          const q = Math.abs(px) - half;\n          let d: number, nx: number, ny: number;\n          if (q <= 0) { d = r - Math.abs(py); nx = 0; ny = py < 0 ? -1 : 1; }\n          else { const l = Math.hypot(q, py) || 1; d = r - l; nx = (px < 0 ? -q : q) / l; ny = py / l; }\n          const i = y * W + x;\n          alpha[i] = Math.max(0, Math.min(1, d + 0.5));\n          gx[i] = nx; gy[i] = ny;\n          const t = Math.max(0, Math.min(1, 1 - d / bevel)); // 1 at the edge, 0 on the flat top\n          rim[i] = t;\n          bend[i] = Math.pow(t, 1.7);\n          gloss[i] = Math.max(0, 1 - (y / H) * 2.4) * (1 - t) * 0.5;\n        }\n      }\n    };\n\n    const state = { press: 0, vel: 0, target: 0, lx: -0.45, ly: -0.89, tlx: -0.45, tly: -0.89, ring: -1, rx: 0, ry: 0, zoom: 1.05 };\n\n    const paint = (now: number) => {\n      if (!out || broken || !img.complete || !img.naturalWidth) return;\n      const { bx, by, bw, bh, cw, ch } = box;\n      const iw = img.naturalWidth, ih = img.naturalHeight;\n      const s0 = Math.max(cw / iw, ch / ih), z = state.zoom;\n      const w = iw * s0, h = ih * s0;\n      const x0 = (cw - w) * FOCUS.x, y0 = (ch - h) * FOCUS.y;\n      bgx.setTransform(RES, 0, 0, RES, PAD - bx * RES, PAD - by * RES);\n      bgx.drawImage(img, cw / 2 + (x0 - cw / 2) * z, ch / 2 + (y0 - ch / 2) * z, w * z, h * z);\n      let src: Uint8ClampedArray;\n      try { src = bgx.getImageData(0, 0, bgW, bgH).data; } catch { broken = true; setLive(false); return; }\n      const dst = out.data;\n      const S = BEND * RES * (1 - 0.55 * state.press);\n      const lx = state.lx, ly = state.ly;\n      const ringOn = state.ring >= 0;\n      const ringR = state.ring * RES, ringAmp = ringOn ? 6 * RES * Math.max(0, 1 - state.ring / (bw * 0.9)) : 0;\n      const cx = W / 2, cy = H / 2, mag = 0.94 + 0.04 * state.press;\n      const maxX = bgW - 1, maxY = bgH - 1;\n      for (let y = 0; y < H; y++) {\n        for (let x = 0; x < W; x++) {\n          const i = y * W + x, o = i * 4, a = alpha[i];\n          if (a <= 0) { dst[o + 3] = 0; continue; }\n          const nx = gx[i], ny = gy[i], t = rim[i];\n          let m = S * bend[i];\n          let ox = 0, oy = 0;\n          if (ringOn) {\n            const dx = x - state.rx, dy = y - state.ry, dist = Math.sqrt(dx * dx + dy * dy) || 1;\n            const k = (dist - ringR) / (19 * RES);\n            if (k > -1 && k < 1) { const wv = Math.sin(k * Math.PI) * ringAmp; ox = (dx / dist) * wv; oy = (dy / dist) * wv; }\n          }\n          const fx = PAD + cx + (x - cx) * mag + ox, fy = PAD + cy + (y - cy) * mag + oy;\n          // Red, green and blue bend by slightly different amounts, which is what puts colour in the rim.\n          let X = fx - nx * m * 0.86, Y = fy - ny * m * 0.86;\n          const r = src[((Y < 0 ? 0 : Y > maxY ? maxY : Y) | 0) * bgW * 4 + ((X < 0 ? 0 : X > maxX ? maxX : X) | 0) * 4];\n          X = fx - nx * m; Y = fy - ny * m;\n          const g = src[((Y < 0 ? 0 : Y > maxY ? maxY : Y) | 0) * bgW * 4 + ((X < 0 ? 0 : X > maxX ? maxX : X) | 0) * 4 + 1];\n          X = fx - nx * m * 1.16; Y = fy - ny * m * 1.16;\n          const b = src[((Y < 0 ? 0 : Y > maxY ? maxY : Y) | 0) * bgW * 4 + ((X < 0 ? 0 : X > maxX ? maxX : X) | 0) * 4 + 2];\n          const facing = nx * lx + ny * ly; // 1 where the edge faces the light\n          const edge = t > 0.7 ? (t - 0.7) / 0.3 : 0;\n          const lit = facing > 0 ? facing * facing : 0;\n          const back = facing < -0.2 ? (-facing - 0.2) * 1.25 : 0;\n          const spec = edge * Math.sqrt(edge) * (lit * 250 + back * back * 150) + (t > 0.9 ? (t - 0.9) * 10 * (50 + lit * 170) : 0) + gloss[i] * 64;\n          // A pale crescent just inside the far rim, where light leaves the glass, and a thin dark line under the lit edge.\n          const inner = t > 0.35 && t < 0.8 ? Math.sin(((t - 0.35) / 0.45) * Math.PI) : 0;\n          const glow = facing < 0 ? inner * facing * facing * 64 : 0;\n          const line = t > 0.62 && t < 0.86 ? Math.sin(((t - 0.62) / 0.24) * Math.PI) * lit * 0.22 : 0;\n          const dark = SMOKE * (1 - line);\n          const add = spec + glow;\n          dst[o] = r * dark + add; dst[o + 1] = g * dark + add; dst[o + 2] = b * dark + add * 0.96; dst[o + 3] = a * 255;\n        }\n      }\n      ctx.putImageData(out, 0, 0);\n      setLive(true);\n      void now;\n    };\n\n    let raf = 0, last = 0, start = 0, seen = true, touched = 0, nextDemo = 1300, demoUp = 0;\n    const pressDown = (x: number, y: number) => { state.target = 1; state.rx = x * RES; state.ry = y * RES; state.ring = -1; };\n    const pressUp = () => { if (state.target === 1) { state.target = 0; state.ring = 0; } };\n\n    const frame = (now: number) => {\n      raf = 0;\n      if (!start) { start = now; last = now; }\n      const dt = Math.min(0.033, (now - last) / 1000); last = now;\n      const t = now - start;\n      // A soft spring carries the press, so the glass overshoots a little on release.\n      const k = 380, damp = 17;\n      state.vel += (k * (state.target - state.press) - damp * state.vel) * dt;\n      state.press += state.vel * dt;\n      if (state.ring >= 0) { state.ring += dt * 430; if (state.ring > box.bw * 0.95) state.ring = -1; }\n      state.zoom = 1.06 + 0.035 * Math.sin(t / 2600);\n      if (now - touched > 2600) {\n        const a = -2.0 + 0.5 * Math.sin(t / 1900);\n        state.tlx = Math.cos(a); state.tly = Math.sin(a);\n        if (t > nextDemo && state.target === 0) { pressDown(box.bw * (0.3 + 0.4 * Math.random()), box.bh / 2); demoUp = t + 240; nextDemo = t + 3000; }\n        if (demoUp && t > demoUp) { demoUp = 0; pressUp(); }\n      }\n      state.lx += (state.tlx - state.lx) * Math.min(1, dt * 7); state.ly += (state.tly - state.ly) * Math.min(1, dt * 7);\n      const p = state.press;\n      sq.style.transform = `translateY(${(p * 2.5).toFixed(2)}px) scale(${(1 + p * 0.028).toFixed(4)}, ${(1 - p * 0.075).toFixed(4)})`;\n      sh.style.opacity = (1 - p * 0.45).toFixed(3);\n      sh.style.transform = `translateY(${(-p * 5).toFixed(2)}px) scale(${(1 - p * 0.04).toFixed(3)})`;\n      img.style.transform = `scale(${state.zoom.toFixed(4)})`;\n      paint(now);\n      if (seen && !document.hidden) raf = requestAnimationFrame(frame);\n    };\n    const wake = () => { if (!raf && !reduce) { last = performance.now(); raf = requestAnimationFrame(frame); } };\n\n    const still = () => { state.zoom = 1.06; img.style.transform = \"scale(1.06)\"; paint(0); };\n    const setup = () => { measure(); if (reduce) still(); else wake(); };\n    setup();\n    if (!img.complete) img.addEventListener(\"load\", setup);\n\n    const local = (e: PointerEvent) => { const b = btn.getBoundingClientRect(); return { x: e.clientX - b.left, y: e.clientY - b.top, b }; };\n    const onMove = (e: PointerEvent) => {\n      const c = cardEl.getBoundingClientRect(), b = btn.getBoundingClientRect();\n      const dx = e.clientX - (b.left + b.width / 2), dy = e.clientY - (b.top + b.height / 2) - 30;\n      const l = Math.hypot(dx, dy) || 1;\n      state.tlx = dx / l; state.tly = dy / l; touched = performance.now();\n      void c;\n      if (reduce) { state.lx = state.tlx; state.ly = state.tly; still(); }\n    };\n    const onDown = (e: PointerEvent) => {\n      touched = performance.now(); const p = local(e); pressDown(p.x, p.y);\n      if (reduce) { state.press = 1; sq.style.transform = \"translateY(2px) scale(1.02, 0.94)\"; still(); }\n    };\n    const onUp = () => {\n      touched = performance.now(); pressUp();\n      if (reduce) { state.press = 0; state.ring = -1; sq.style.transform = \"\"; still(); }\n    };\n    const onKeyDown = (e: KeyboardEvent) => { if ((e.key === \" \" || e.key === \"Enter\") && !e.repeat) { touched = performance.now(); pressDown(box.bw / 2, box.bh / 2); if (reduce) { state.press = 1; still(); } } };\n    const onKeyUp = (e: KeyboardEvent) => { if (e.key === \" \" || e.key === \"Enter\") onUp(); };\n    cardEl.addEventListener(\"pointermove\", onMove);\n    btn.addEventListener(\"pointerdown\", onDown);\n    window.addEventListener(\"pointerup\", onUp);\n    window.addEventListener(\"pointercancel\", onUp);\n    btn.addEventListener(\"keydown\", onKeyDown);\n    btn.addEventListener(\"keyup\", onKeyUp);\n    btn.addEventListener(\"blur\", onUp);\n\n    const ro = new ResizeObserver(setup);\n    ro.observe(cardEl);\n    const io = new IntersectionObserver(([entry]) => { seen = entry.isIntersecting; if (seen) wake(); });\n    io.observe(cardEl);\n    const onVis = () => { if (!document.hidden) wake(); };\n    document.addEventListener(\"visibilitychange\", onVis);\n\n    return () => {\n      cancelAnimationFrame(raf);\n      img.removeEventListener(\"load\", setup);\n      cardEl.removeEventListener(\"pointermove\", onMove);\n      btn.removeEventListener(\"pointerdown\", onDown);\n      window.removeEventListener(\"pointerup\", onUp);\n      window.removeEventListener(\"pointercancel\", onUp);\n      btn.removeEventListener(\"keydown\", onKeyDown);\n      btn.removeEventListener(\"keyup\", onKeyUp);\n      btn.removeEventListener(\"blur\", onUp);\n      ro.disconnect(); io.disconnect();\n      document.removeEventListener(\"visibilitychange\", onVis);\n    };\n  }, []);\n\n  return (\n    <div className=\"flex min-h-[660px] w-full flex-col items-center justify-center bg-[#ece8e1] px-4 py-12\">\n      <div ref={card} className=\"relative h-[430px] w-[300px] overflow-hidden rounded-[30px] bg-[#c9461c] shadow-[0_40px_70px_-30px_rgba(74,32,10,0.55),0_2px_0_rgba(255,255,255,0.6)_inset] sm:h-[480px] sm:w-[350px]\">\n        <img ref={photo} src={PHOTO} alt={PHOTO_ALT} crossOrigin=\"anonymous\" width={1000} height={1498} className=\"absolute inset-0 h-full w-full object-cover will-change-transform\" style={{ objectPosition: `${FOCUS.x * 100}% ${FOCUS.y * 100}%` }} />\n\n        <div className=\"absolute inset-x-0 bottom-7 flex justify-center\">\n          <span className=\"relative block h-[76px] w-[236px] sm:w-[268px]\">\n            {/* The shadow the glass throws on the photo, and the light it gathers underneath. */}\n            <span ref={shadow} aria-hidden=\"true\" className=\"pointer-events-none absolute inset-0 rounded-full shadow-[0_26px_34px_-10px_rgba(50,10,0,0.7),0_9px_12px_-3px_rgba(50,10,0,0.55)]\" />\n            <span aria-hidden=\"true\" className=\"pointer-events-none absolute inset-x-10 -bottom-2.5 h-4 rounded-full bg-[#ffe6c2] opacity-70 blur-[7px]\" />\n            <span ref={squash} className=\"absolute inset-0 block will-change-transform\">\n              <button\n                ref={button}\n                type=\"button\"\n                onClick={() => setCount((c) => c + 1)}\n                className={`group relative flex h-full w-full touch-manipulation select-none items-center justify-center gap-2.5 overflow-hidden rounded-full text-[17px] font-semibold tracking-tight text-white outline-none focus-visible:ring-2 focus-visible:ring-white focus-visible:ring-offset-2 focus-visible:ring-offset-[#c9461c] ${live ? \"\" : \"border border-white/50 bg-black/25 backdrop-blur-md\"}`}\n              >\n                <canvas ref={canvas} aria-hidden=\"true\" className={`pointer-events-none absolute inset-0 h-full w-full ${live ? \"opacity-100\" : \"opacity-0\"}`} />\n                <span className=\"relative [text-shadow:0_1px_2px_rgba(60,20,0,0.75),0_0_14px_rgba(60,20,0,0.45)]\">{LABEL}</span>\n                <svg viewBox=\"0 0 20 20\" aria-hidden=\"true\" className=\"relative h-[18px] w-[18px] drop-shadow-[0_1px_2px_rgba(60,20,0,0.75)] transition-transform duration-300 group-hover:translate-x-0.5 motion-reduce:transition-none\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\"><path d=\"M4 10h12M11 5l5 5-5 5\" /></svg>\n              </button>\n            </span>\n          </span>\n        </div>\n      </div>\n      <p className=\"mt-7 text-center text-[13px] font-medium tracking-wide text-stone-600\">{CAPTION}</p>\n      <p className=\"sr-only\" aria-live=\"polite\">{count > 0 ? `Fitting request sent ${count} ${count === 1 ? \"time\" : \"times\"}.` : \"\"}</p>\n    </div>\n  );\n}\n"}]}
