{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"portrait-studio-hero-with-a-giant-headline-that-passes-behind-the-sitter-and-in-front-of-her","type":"registry:block","title":"Portrait Studio Hero with a Giant Headline That Passes Behind the Sitter and in Front of Her","description":"Hero with a giant headline around a studio portrait: one word passes behind the sitter and one in front, cut out in the browser. Free React and HTML code.","dependencies":["framer-motion"],"files":[{"path":"components/we-inc/portrait-studio-hero-with-a-giant-headline-that-passes-behind-the-sitter-and-in-front-of-her.tsx","type":"registry:component","content":"import { useEffect, useRef, useState } from \"react\";\nimport type { PointerEvent as ReactPointerEvent } from \"react\";\nimport { motion, useAnimationFrame, useMotionValue, useReducedMotion, useSpring, useTransform } from \"framer-motion\";\n\n// Everything a visitor would change lives here. The photograph must be shot against one plain backdrop colour.\nconst hero = {\n  studio: \"Face Value\",\n  place: \"Portrait studio, Leith\",\n  behind: \"FACE\",\n  inFront: \"VALUE\",\n  line: \"One sitter, one hour, one roll of film. Sittings by appointment, Tuesday to Saturday.\",\n  button: \"Book a sitting\",\n  photo: \"https://images.pexels.com/photos/32174976/pexels-photo-32174976.jpeg?auto=compress&cs=tinysrgb&w=1100\",\n  alt: \"A woman with a round afro and tassel earrings in a black top, both hands raised to her hair, looking past the camera\",\n};\n\n/** How far a pixel must be from the backdrop colour to start counting as the sitter, and where it is fully her. */\nconst KEY_FROM = 26;\nconst KEY_TO = 70;\n/** Width the backdrop is studied at. The cut-out itself is drawn at the photo's full size. */\nconst STUDY = 560;\n/** Enclosed backdrop-coloured patches smaller than this many studied pixels are kept as part of the sitter. */\nconst POCKET = 140;\n\n/** Solves a small set of linear equations in place. Used to fit a smooth backdrop colour across the frame. */\nfunction solve(m: number[][], v: number[]) {\n  const n = v.length;\n  for (let c = 0; c < n; c++) {\n    let best = c;\n    for (let r = c + 1; r < n; r++) if (Math.abs(m[r][c]) > Math.abs(m[best][c])) best = r;\n    [m[c], m[best]] = [m[best], m[c]];\n    [v[c], v[best]] = [v[best], v[c]];\n    const d = m[c][c] || 1e-9;\n    for (let r = c + 1; r < n; r++) {\n      const f = m[r][c] / d;\n      for (let k = c; k < n; k++) m[r][k] -= f * m[c][k];\n      v[r] -= f * v[c];\n    }\n  }\n  const out = new Array<number>(n).fill(0);\n  for (let r = n - 1; r >= 0; r--) {\n    let s = v[r];\n    for (let k = r + 1; k < n; k++) s -= m[r][k] * out[k];\n    out[r] = s / (m[r][r] || 1e-9);\n  }\n  return out;\n}\n\n/**\n * Lifts the sitter off a plain backdrop. It learns the backdrop from the top and side margins of the frame\n * (including any soft falloff of light across it), then keeps everything that is not backdrop, plus any\n * backdrop-coloured patch that the backdrop cannot reach from the edges (lips, a red earring).\n */\nfunction cutOut(img: HTMLImageElement, target: HTMLCanvasElement) {\n  const w = STUDY;\n  const h = Math.round((STUDY * img.naturalHeight) / img.naturalWidth);\n  const small = document.createElement(\"canvas\");\n  small.width = w;\n  small.height = h;\n  const sc = small.getContext(\"2d\", { willReadFrequently: true });\n  const out = target.getContext(\"2d\");\n  if (!sc || !out) return false;\n  sc.drawImage(img, 0, 0, w, h);\n  const px = sc.getImageData(0, 0, w, h);\n  const d = px.data;\n\n  const terms = (x: number, y: number) => [1, x, y, x * x, y * y, x * y];\n  const inMargin = (x: number, y: number) => y < h * 0.8 && (y < h * 0.06 || x < w * 0.04 || x > w * 0.96);\n  // A first rough backdrop colour, so that anything else in the margins (a sleeve, a shoulder) is left out of the fit.\n  let n = 0;\n  const mean = [0, 0, 0];\n  for (let y = 0; y < h; y += 3)\n    for (let x = 0; x < w; x += 3)\n      if (inMargin(x, y) && y < h * 0.3) {\n        const i = (y * w + x) * 4;\n        mean[0] += d[i];\n        mean[1] += d[i + 1];\n        mean[2] += d[i + 2];\n        n++;\n      }\n  if (!n) return false;\n  mean.forEach((_, c) => (mean[c] /= n));\n\n  const A = Array.from({ length: 6 }, () => new Array<number>(6).fill(0));\n  const B = [new Array<number>(6).fill(0), new Array<number>(6).fill(0), new Array<number>(6).fill(0)];\n  for (let y = 0; y < h; y += 2)\n    for (let x = 0; x < w; x += 2) {\n      if (!inMargin(x, y)) continue;\n      const i = (y * w + x) * 4;\n      if (Math.abs(d[i] - mean[0]) + Math.abs(d[i + 1] - mean[1]) + Math.abs(d[i + 2] - mean[2]) > 110) continue;\n      const t = terms(x / w, y / h);\n      for (let a = 0; a < 6; a++) {\n        for (let b = 0; b < 6; b++) A[a][b] += t[a] * t[b];\n        for (let c = 0; c < 3; c++) B[c][a] += t[a] * d[i + c];\n      }\n    }\n  const fit = B.map((b) => solve(A.map((row) => row.slice()), b.slice()));\n\n  const total = w * h;\n  const alpha = new Float32Array(total);\n  for (let y = 0; y < h; y++)\n    for (let x = 0; x < w; x++) {\n      const i = y * w + x;\n      const t = terms(x / w, y / h);\n      let dist = 0;\n      for (let c = 0; c < 3; c++) {\n        let bg = 0;\n        for (let a = 0; a < 6; a++) bg += fit[c][a] * t[a];\n        const diff = d[i * 4 + c] - bg;\n        dist += diff * diff;\n      }\n      const k = Math.min(1, Math.max(0, (Math.sqrt(dist) - KEY_FROM) / (KEY_TO - KEY_FROM)));\n      // The top sliver of a studio frame often catches the edge of the paper roll, so it is dropped.\n      alpha[i] = y < h * 0.03 ? 0 : k * k * (3 - 2 * k);\n    }\n\n  // Flood in from the top and sides: only backdrop that connects to the edge of the frame is removed.\n  const reached = new Uint8Array(total);\n  const stack = new Int32Array(total);\n  let top = 0;\n  const visit = (i: number) => {\n    if (!reached[i] && alpha[i] < 0.999) {\n      reached[i] = 1;\n      stack[top++] = i;\n    }\n  };\n  for (let x = 0; x < w; x++) visit(x);\n  for (let y = 0; y < h; y++) {\n    visit(y * w);\n    visit(y * w + w - 1);\n  }\n  while (top) {\n    const i = stack[--top];\n    const x = i % w;\n    if (x > 0) visit(i - 1);\n    if (x < w - 1) visit(i + 1);\n    if (i >= w) visit(i - w);\n    if (i < total - w) visit(i + w);\n  }\n  // Backdrop the flood could not reach (the gap between an arm and the neck) is also removed, but only when the\n  // patch is clearly backdrop and big enough not to be a mouth or a bead.\n  const patch = new Int32Array(total);\n  for (let start = 0; start < total; start++) {\n    if (reached[start] || alpha[start] > 0.2) continue;\n    let size = 0;\n    top = 0;\n    reached[start] = 2;\n    stack[top++] = start;\n    while (top) {\n      const i = stack[--top];\n      patch[size++] = i;\n      const x = i % w;\n      const near = [x > 0 ? i - 1 : -1, x < w - 1 ? i + 1 : -1, i - w, i + w];\n      for (const j of near)\n        if (j >= 0 && j < total && !reached[j] && alpha[j] <= 0.2) {\n          reached[j] = 2;\n          stack[top++] = j;\n        }\n    }\n    if (size < POCKET) for (let k = 0; k < size; k++) reached[patch[k]] = 3;\n  }\n  for (let i = 0; i < total; i++) {\n    d[i * 4 + 3] = Math.round((reached[i] === 1 || reached[i] === 2 ? alpha[i] : 1) * 255);\n  }\n  sc.putImageData(px, 0, 0);\n\n  target.width = img.naturalWidth;\n  target.height = img.naturalHeight;\n  out.drawImage(img, 0, 0);\n  out.globalCompositeOperation = \"destination-in\";\n  out.imageSmoothingEnabled = true;\n  out.imageSmoothingQuality = \"high\";\n  out.drawImage(small, 0, 0, target.width, target.height);\n  out.globalCompositeOperation = \"source-over\";\n  return true;\n}\n\nexport default function PortraitStudioHeroWithAGiantHeadlineThatPassesBehindTheSitterAndInFrontOfHer() {\n  const reduce = useReducedMotion();\n  const stage = useRef<HTMLElement>(null);\n  const photo = useRef<HTMLImageElement>(null);\n  const canvas = useRef<HTMLCanvasElement>(null);\n  const backWord = useRef<HTMLSpanElement>(null);\n  const frontWord = useRef<HTMLSpanElement>(null);\n  /** \"cut\" once the sitter has been lifted off her backdrop, \"plain\" if the photo could not be read. */\n  const [state, setState] = useState<\"wait\" | \"cut\" | \"plain\">(\"wait\");\n  const steered = useRef(-1e6);\n\n  // One shared pointer position, from -1 to 1 each way. Each layer moves by a different amount of it.\n  const px = useMotionValue(0);\n  const py = useMotionValue(0);\n  const sx = useSpring(px, { stiffness: 60, damping: 16, mass: 1.1 });\n  const sy = useSpring(py, { stiffness: 60, damping: 16, mass: 1.1 });\n  /** Narrow screens get a smaller swing, so the front word never leaves the frame. */\n  const reach = useRef(1);\n  const backX = useTransform(sx, (v) => v * -26 * reach.current);\n  const backY = useTransform(sy, (v) => v * -10 * reach.current);\n  const midX = useTransform(sx, (v) => v * 12 * reach.current);\n  const midY = useTransform(sy, (v) => v * 5 * reach.current);\n  const frontX = useTransform(sx, (v) => v * 46 * reach.current);\n  const frontY = useTransform(sy, (v) => v * 16 * reach.current);\n  const shadow = useTransform([sx, sy], ([x, y]: number[]) => `drop-shadow(${-30 - x * 22}px ${20 - y * 10}px 26px rgba(60,2,6,0.62))`);\n\n  // With nobody steering, the camera drifts a little from side to side so the three layers keep sliding apart.\n  useAnimationFrame((t) => {\n    if (reduce || performance.now() - steered.current < 2400) return;\n    px.set(Math.sin(t / 2300 + 0.9) * 0.8);\n    py.set(Math.sin(t / 3100) * 0.5);\n  });\n\n  useEffect(() => {\n    const img = photo.current;\n    const cv = canvas.current;\n    if (!img || !cv) return;\n    const run = () => {\n      if (!img.naturalWidth) return;\n      try {\n        setState(cutOut(img, cv) ? \"cut\" : \"plain\");\n      } catch {\n        // The photo host did not let the page read the picture: show it uncut, with the whole headline in front.\n        setState(\"plain\");\n      }\n    };\n    const fail = () => setState(\"plain\");\n    if (img.complete) run();\n    img.addEventListener(\"load\", run);\n    img.addEventListener(\"error\", fail);\n    return () => {\n      img.removeEventListener(\"load\", run);\n      img.removeEventListener(\"error\", fail);\n    };\n  }, []);\n\n  // Both words are set to the same measure, like a poster, whatever font the visitor's system supplies.\n  useEffect(() => {\n    const el = stage.current;\n    if (!el) return;\n    const fitWords = () => {\n      const measure = Math.min(el.clientWidth * 0.8, 960);\n      reach.current = Math.min(1, el.clientWidth / 1200);\n      [backWord.current, frontWord.current].forEach((word) => {\n        if (!word) return;\n        word.style.fontSize = \"100px\";\n        const wide = word.getBoundingClientRect().width || 1;\n        word.style.fontSize = `${(100 * measure) / wide}px`;\n      });\n    };\n    fitWords();\n    const ro = new ResizeObserver(fitWords);\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, []);\n\n  function steer(e: ReactPointerEvent<HTMLElement>) {\n    if (reduce) return;\n    const r = e.currentTarget.getBoundingClientRect();\n    px.set(((e.clientX - r.left) / r.width) * 2 - 1);\n    py.set(((e.clientY - r.top) / r.height) * 2 - 1);\n    steered.current = performance.now();\n  }\n\n  const word = \"block whitespace-nowrap font-sans font-black leading-[0.76] tracking-[-0.065em] text-[#fff6ec] will-change-transform\";\n\n  return (\n    <section\n      ref={stage}\n      onPointerMove={steer}\n      className=\"relative isolate h-[640px] w-full overflow-hidden bg-[#d62a28] sm:h-[800px]\"\n    >\n      <div aria-hidden=\"true\" className=\"absolute inset-0 -z-10\" style={{ background: \"radial-gradient(70% 60% at 50% 38%, #ea3a33 0%, #d62a28 45%, #b01c20 100%)\" }} />\n\n      <header className=\"absolute inset-x-0 top-0 z-40 flex items-center justify-between px-5 pt-5 text-[13px] font-medium text-[#fff6ec] sm:px-10 sm:pt-8\">\n        <span className=\"font-semibold tracking-tight\">{hero.studio}</span>\n        <span>{hero.place}</span>\n      </header>\n\n      <h1 className=\"sr-only\">\n        {hero.behind} {hero.inFront}\n      </h1>\n\n      {/* Furthest away: the first word, a touch soft, with the sitter's shadow falling across it. */}\n      <motion.div aria-hidden=\"true\" style={{ x: backX, y: backY }} className=\"absolute inset-x-0 top-[12%] z-10 flex justify-center sm:top-[5%]\">\n        <span ref={backWord} className={`${word} text-[31vw] blur-[0.6px]`}>\n          {hero.behind}\n        </span>\n      </motion.div>\n\n      {/* In the middle: the sitter, standing on the bottom edge of the section. */}\n      <div className=\"absolute inset-x-0 bottom-[-12px] z-20 flex h-[80%] justify-center sm:h-[94%]\">\n      <motion.div style={{ x: midX, y: midY }} className=\"relative aspect-[900/1353] h-full\">\n        <img\n          ref={photo}\n          src={hero.photo}\n          alt={hero.alt}\n          crossOrigin=\"anonymous\"\n          width={1100}\n          height={1654}\n          className={`absolute inset-0 h-full w-full object-cover transition-opacity duration-300 ${state === \"plain\" ? \"opacity-100\" : \"opacity-0\"}`}\n          style={{ maskImage: \"radial-gradient(75% 70% at 50% 55%, #000 60%, transparent 100%)\", WebkitMaskImage: \"radial-gradient(75% 70% at 50% 55%, #000 60%, transparent 100%)\" }}\n        />\n        <motion.canvas\n          ref={canvas}\n          aria-hidden=\"true\"\n          style={{ filter: shadow }}\n          className={`absolute inset-0 h-full w-full transition-opacity duration-500 ${state === \"cut\" ? \"opacity-100\" : \"opacity-0\"}`}\n        />\n      </motion.div>\n      </div>\n\n      {/* Nearest: the second word, crossing in front of her and throwing its own shadow back onto her. */}\n      <motion.div aria-hidden=\"true\" style={{ x: frontX, y: frontY }} className=\"absolute inset-x-0 bottom-[21%] z-30 flex justify-center sm:bottom-[15%]\">\n        <span ref={frontWord} className={`${word} text-[25vw]`} style={{ textShadow: \"-14px 22px 34px rgba(40,2,6,0.55), -2px 3px 4px rgba(40,2,6,0.35)\" }}>\n          {hero.inFront}\n        </span>\n      </motion.div>\n\n      <div className=\"absolute inset-x-0 bottom-0 z-40 flex items-end justify-between gap-4 px-5 pb-5 sm:px-10 sm:pb-8\">\n        <p className=\"max-w-[15rem] text-[13px] font-medium leading-snug text-[#fff6ec] sm:max-w-xs sm:text-[15px]\">{hero.line}</p>\n        <a\n          href=\"#\"\n          className=\"inline-flex h-11 shrink-0 items-center rounded-full bg-[#fff6ec] px-5 text-[14px] font-semibold text-[#3a0709] shadow-[0_10px_24px_-10px_rgba(40,2,6,0.8)] transition-transform duration-200 hover:-translate-y-0.5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white focus-visible:ring-offset-2 focus-visible:ring-offset-[#b01c20] motion-reduce:transition-none sm:h-12 sm:px-7 sm:text-[15px]\"\n        >\n          {hero.button}\n        </a>\n      </div>\n    </section>\n  );\n}\n"}]}
