{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"portrait-print-with-a-liquid-glass-bead-that-chases-the-pointer-and-shows-a-second-photograph","type":"registry:block","title":"Portrait Print with a Liquid Glass Bead That Chases the Pointer and Shows a Second Photograph","description":"Image reveal in WebGL: a bead of liquid glass chases the cursor across a portrait and shows another photo refracted inside. Free React and HTML code.","dependencies":["framer-motion"],"files":[{"path":"components/we-inc/portrait-print-with-a-liquid-glass-bead-that-chases-the-pointer-and-shows-a-second-photograph.tsx","type":"registry:component","content":"import { useEffect, useRef, useState } from \"react\";\nimport type { KeyboardEvent as ReactKeyboardEvent, PointerEvent as ReactPointerEvent } from \"react\";\nimport { useReducedMotion } from \"framer-motion\";\n\n// Two pictures of the same size. The first is the print, the second is what the bead shows.\nconst looks = [\n  {\n    name: \"Cobalt\",\n    src: \"https://images.pexels.com/photos/30755158/pexels-photo-30755158.jpeg?auto=compress&cs=tinysrgb&w=900\",\n    alt: \"A woman with her hair bound into a tall stack of spheres, in a pale blue oversized shirt against a blue wall, one hand at her jaw\",\n  },\n  {\n    name: \"Tangerine\",\n    src: \"https://images.pexels.com/photos/39325161/pexels-photo-39325161.jpeg?auto=compress&cs=tinysrgb&w=900\",\n    alt: \"A woman with cropped hair in an orange top and long white wrapped gloves against an orange wall\",\n  },\n];\n\n/** Size of each drop as a share of the print's height. The first leads, the rest trail behind and melt back in. */\nconst DROPS = [0.15, 0.084, 0.068, 0.054, 0.043, 0.034];\n/** How quickly each drop catches up. Lower numbers lag further, so a fast move strings the bead out. */\nconst PULL = [130, 62, 44, 31, 22, 15];\n\nconst VERT = `attribute vec2 a; void main(){ gl_Position = vec4(a, 0.0, 1.0); }`;\n\nconst FRAG = `precision highp float;\nuniform vec2 u_res;\nuniform sampler2D u_a;\nuniform sampler2D u_b;\nuniform vec2 u_img;\nuniform vec3 u_drops[6];\nuniform float u_time;\nuniform float u_swap;\n\nvec2 cover(vec2 uv, float img){\n  float A = u_res.x / u_res.y;\n  vec2 t = uv;\n  if (img > A) t.x = (uv.x - 0.5) * A / img + 0.5;\n  else t.y = (uv.y - 0.5) * img / A + 0.5;\n  return clamp(t, 0.0, 1.0);\n}\n// The bead is a sum of soft fields, one per drop. Where the sum passes 1 there is liquid.\nfloat field(vec2 p, float A, out vec2 grad){\n  float f = 0.0;\n  grad = vec2(0.0);\n  for (int i = 0; i < 6; i++){\n    vec2 d = p - vec2(u_drops[i].x * A, u_drops[i].y);\n    float d2 = dot(d, d) + 0.00002;\n    float r2 = u_drops[i].z * u_drops[i].z;\n    f += r2 / d2;\n    grad -= 2.0 * r2 * d / (d2 * d2);\n  }\n  return f;\n}\nvec3 outside(vec2 uv){ return mix(texture2D(u_a, cover(uv, u_img.x)).rgb, texture2D(u_b, cover(uv, u_img.y)).rgb, u_swap); }\nvec3 inside(vec2 uv){ return mix(texture2D(u_b, cover(uv, u_img.y)).rgb, texture2D(u_a, cover(uv, u_img.x)).rgb, u_swap); }\n\nvoid main(){\n  vec2 uv = vec2(gl_FragCoord.x / u_res.x, 1.0 - gl_FragCoord.y / u_res.y);\n  float A = u_res.x / u_res.y;\n  vec2 p = vec2(uv.x * A, uv.y);\n  // A slow wobble so the outline never sits perfectly round.\n  p += 0.006 * vec2(sin(p.y * 13.0 + u_time * 1.3), cos(p.x * 11.0 - u_time * 1.1));\n\n  vec2 g;\n  float f = field(p, A, g);\n  float gl = length(g) + 0.0001;\n  vec2 out_ = -g / gl;\n  vec2 light = normalize(vec2(-0.55, -0.83));\n\n  // The print, with the bead's shadow lying on it away from the light.\n  vec2 gs;\n  float fs = field(p + light * 0.022, A, gs);\n  vec3 base = outside(uv);\n  base *= 1.0 - 0.50 * smoothstep(0.62, 1.12, fs);\n  // Light that has passed through the bead lands as a bright crescent just beyond it.\n  vec2 gc;\n  float fc = field(p + light * 0.006, A, gc);\n  base += vec3(1.0, 0.96, 0.9) * 0.20 * smoothstep(0.90, 1.0, fc) * (1.0 - smoothstep(1.0, 1.05, f)) * max(dot(out_, -light), 0.0);\n\n  // Inside: 0 at the rim, 1 where the dome is flat on top.\n  float k = clamp((f - 1.0) / 1.6, 0.0, 1.0);\n  float steep = pow(1.0 - k, 2.4);\n  vec2 lens = out_ * steep;\n  vec2 pull = vec2(lens.x / A, lens.y);\n  vec3 seen;\n  seen.r = inside(uv - pull * 0.060).r;\n  seen.g = inside(uv - pull * 0.065).g;\n  seen.b = inside(uv - pull * 0.070).b;\n  // The far side of a drop glows and the side nearest the light is shaded.\n  seen *= 1.0 + 0.55 * steep * dot(out_, -light);\n  seen += vec3(1.0) * 0.16 * pow(1.0 - k, 7.0);\n  // Two reflections of the lamp: a hard one near the rim and a soft bounce opposite.\n  vec3 n = normalize(vec3(lens * 1.5, 1.0));\n  float hit = max(dot(n, normalize(vec3(light * 1.05, 0.72))), 0.0);\n  seen += vec3(1.0) * smoothstep(0.972, 0.992, hit) * 0.95;\n  seen += vec3(1.0) * pow(hit, 9.0) * 0.16;\n  // A long soft streak of the studio window curving round the shoulder of the bead.\n  float facing = dot(out_, light);\n  float band = smoothstep(0.30, 0.46, steep) * (1.0 - smoothstep(0.50, 0.74, steep));\n  seen += vec3(1.0) * band * smoothstep(0.45, 0.95, facing) * 0.34;\n  float bounce = max(dot(n, normalize(vec3(-light * 1.2, 0.6))), 0.0);\n  seen += vec3(1.0, 0.97, 0.92) * smoothstep(0.93, 0.99, bounce) * 0.22;\n\n  float edge = gl * 1.6 / u_res.y;\n  float cut = smoothstep(1.0 - edge, 1.0 + edge, f);\n  // A hairline of dark where the liquid meets the paper.\n  base *= 1.0 - 0.35 * smoothstep(1.0 - edge * 5.0, 1.0, f) * (1.0 - cut);\n  gl_FragColor = vec4(mix(base, seen, cut), 1.0);\n}`;\n\nexport default function PortraitPrintWithALiquidGlassBeadThatChasesThePointerAndShowsASecondPhotograph() {\n  const reduce = useReducedMotion();\n  const frame = useRef<HTMLButtonElement>(null);\n  const canvas = useRef<HTMLCanvasElement>(null);\n  const first = useRef<HTMLImageElement>(null);\n  const second = useRef<HTMLImageElement>(null);\n  /** Where the bead is heading (0 to 1 each way) and when a person last steered it. */\n  const aim = useRef({ x: 0.6, y: 0.36, at: -1e6 });\n  const flip = useRef(0);\n  const [live, setLive] = useState(false);\n  const [swapped, setSwapped] = useState(false);\n\n  useEffect(() => {\n    flip.current = swapped ? 1 : 0;\n  }, [swapped]);\n\n  useEffect(() => {\n    const el = frame.current;\n    const cv = canvas.current;\n    const one = first.current;\n    const two = second.current;\n    if (reduce || !el || !cv || !one || !two) return;\n    const gl = cv.getContext(\"webgl\", { antialias: false, alpha: false });\n    if (!gl) return;\n\n    const compile = (type: number, source: string) => {\n      const shader = gl.createShader(type)!;\n      gl.shaderSource(shader, source);\n      gl.compileShader(shader);\n      return shader;\n    };\n    const program = gl.createProgram()!;\n    gl.attachShader(program, compile(gl.VERTEX_SHADER, VERT));\n    gl.attachShader(program, compile(gl.FRAGMENT_SHADER, FRAG));\n    gl.linkProgram(program);\n    if (!gl.getProgramParameter(program, gl.LINK_STATUS)) return;\n    gl.useProgram(program);\n    gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());\n    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW);\n    const at = gl.getAttribLocation(program, \"a\");\n    gl.enableVertexAttribArray(at);\n    gl.vertexAttribPointer(at, 2, gl.FLOAT, false, 0, 0);\n    const u = (name: string) => gl.getUniformLocation(program, name);\n    gl.uniform1i(u(\"u_a\"), 0);\n    gl.uniform1i(u(\"u_b\"), 1);\n    const uni = { res: u(\"u_res\"), img: u(\"u_img\"), drops: u(\"u_drops[0]\"), time: u(\"u_time\"), swap: u(\"u_swap\") };\n\n    const n = DROPS.length;\n    const pos = new Float32Array(n * 2);\n    const vel = new Float32Array(n * 2);\n    const packed = new Float32Array(n * 3);\n    for (let i = 0; i < n; i++) pos.set([aim.current.x, aim.current.y], i * 2);\n\n    let ready = false;\n    let visible = true;\n    let raf = 0;\n    let last = 0;\n    let swap = flip.current;\n    const started = performance.now();\n\n    const upload = () => {\n      if (ready || !one.complete || !two.complete || !one.naturalWidth || !two.naturalWidth) return;\n      try {\n        [one, two].forEach((img, unit) => {\n          gl.activeTexture(gl.TEXTURE0 + unit);\n          gl.bindTexture(gl.TEXTURE_2D, gl.createTexture());\n          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n          gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, img);\n        });\n        gl.uniform2f(uni.img, one.naturalWidth / one.naturalHeight, two.naturalWidth / two.naturalHeight);\n        ready = true;\n        setLive(true);\n      } catch {\n        // A picture could not be read into the shader: the still version underneath stays on show.\n        ready = false;\n      }\n    };\n\n    const resize = () => {\n      const ratio = Math.min(window.devicePixelRatio || 1, 2);\n      cv.width = Math.max(1, Math.round(el.clientWidth * ratio));\n      cv.height = Math.max(1, Math.round(el.clientHeight * ratio));\n      gl.viewport(0, 0, cv.width, cv.height);\n    };\n\n    const loop = (stamp: number) => {\n      if (ready) {\n        const t = (stamp - started) / 1000;\n        const dt = Math.min(last ? (stamp - last) / 1000 : 0.016, 0.033);\n        last = stamp;\n        const A = cv.width / cv.height;\n        // With nobody steering, the bead wanders the print in a slow, uneven loop.\n        let tx = aim.current.x;\n        let ty = aim.current.y;\n        if (stamp - aim.current.at > 2200) {\n          tx = 0.5 + 0.25 * Math.sin(t * 0.9 + 0.4) + 0.05 * Math.sin(t * 2.3);\n          ty = 0.42 + 0.22 * Math.sin(t * 0.63 + 1.9) + 0.04 * Math.cos(t * 1.9);\n        }\n        for (let i = 0; i < n; i++) {\n          // Each trailing drop orbits a little way off the one ahead, which keeps the merged outline lobed.\n          const reach = i === 0 ? 0 : 0.034 + i * 0.006;\n          const turn = t * (0.7 + i * 0.23) + i * 2.1;\n          const gx = i === 0 ? tx : pos[(i - 1) * 2] + (Math.cos(turn) * reach) / A;\n          const gy = i === 0 ? ty : pos[(i - 1) * 2 + 1] + Math.sin(turn) * reach;\n          const k = PULL[i];\n          const drag = 2 * Math.sqrt(k) * (i === 0 ? 0.62 : 0.8);\n          vel[i * 2] += ((gx - pos[i * 2]) * k - vel[i * 2] * drag) * dt;\n          vel[i * 2 + 1] += ((gy - pos[i * 2 + 1]) * k - vel[i * 2 + 1] * drag) * dt;\n          pos[i * 2] += vel[i * 2] * dt;\n          pos[i * 2 + 1] += vel[i * 2 + 1] * dt;\n          packed.set([pos[i * 2], pos[i * 2 + 1], DROPS[i]], i * 3);\n        }\n        swap += (flip.current - swap) * Math.min(1, dt * 7);\n        gl.uniform2f(uni.res, cv.width, cv.height);\n        gl.uniform3fv(uni.drops, packed);\n        gl.uniform1f(uni.time, t);\n        gl.uniform1f(uni.swap, swap);\n        gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);\n      }\n      raf = visible && !document.hidden ? requestAnimationFrame(loop) : 0;\n    };\n    const wake = () => {\n      if (!raf && visible && !document.hidden) {\n        last = 0;\n        raf = requestAnimationFrame(loop);\n      }\n    };\n\n    const ro = new ResizeObserver(resize);\n    ro.observe(el);\n    const io = new IntersectionObserver(([entry]) => {\n      visible = entry.isIntersecting;\n      wake();\n    });\n    io.observe(el);\n    document.addEventListener(\"visibilitychange\", wake);\n    one.addEventListener(\"load\", upload);\n    two.addEventListener(\"load\", upload);\n    upload();\n    resize();\n    wake();\n\n    return () => {\n      cancelAnimationFrame(raf);\n      ro.disconnect();\n      io.disconnect();\n      document.removeEventListener(\"visibilitychange\", wake);\n      one.removeEventListener(\"load\", upload);\n      two.removeEventListener(\"load\", upload);\n    };\n  }, [reduce]);\n\n  function steer(e: ReactPointerEvent<HTMLButtonElement>) {\n    const r = e.currentTarget.getBoundingClientRect();\n    aim.current = { x: (e.clientX - r.left) / r.width, y: (e.clientY - r.top) / r.height, at: performance.now() };\n  }\n  /** Arrow keys roll the bead. Enter and Space, like a click, swap the two pictures. */\n  function onKey(e: ReactKeyboardEvent<HTMLButtonElement>) {\n    const move: Record<string, [number, number]> = { ArrowLeft: [-0.08, 0], ArrowRight: [0.08, 0], ArrowUp: [0, -0.07], ArrowDown: [0, 0.07] };\n    const by = move[e.key];\n    if (!by) return;\n    e.preventDefault();\n    const a = aim.current;\n    aim.current = { x: Math.min(0.9, Math.max(0.1, a.x + by[0])), y: Math.min(0.9, Math.max(0.1, a.y + by[1])), at: performance.now() + 4000 };\n  }\n\n  const [under, over] = swapped ? [looks[1], looks[0]] : looks;\n\n  return (\n    <section className=\"relative isolate flex min-h-[760px] w-full flex-col items-center justify-center overflow-hidden bg-[#0b0b0d] px-4 py-14\">\n      <style>{`\n        .lgb-still { clip-path: circle(21% at 61% 35%); }\n        .lgb-ring { left: 61%; top: 35%; width: 52.5%; aspect-ratio: 1; transform: translate(-50%, -50%); }\n      `}</style>\n      <div aria-hidden=\"true\" className=\"absolute inset-0 -z-10\" style={{ background: \"radial-gradient(60% 50% at 50% 42%, #1b1d24 0%, #0b0b0d 70%)\" }} />\n\n      <button\n        ref={frame}\n        type=\"button\"\n        aria-pressed={swapped}\n        aria-label={`Swap the two portraits. ${under.name} is the print and ${over.name} shows through the bead. Arrow keys move the bead.`}\n        onClick={() => setSwapped((s) => !s)}\n        onPointerMove={steer}\n        onPointerDown={steer}\n        onKeyDown={onKey}\n        className=\"relative block aspect-[4/5] w-[min(82vw,420px)] cursor-pointer touch-pan-y overflow-hidden rounded-[10px] bg-[#16171c] shadow-[0_60px_90px_-40px_rgba(0,0,0,0.9),0_0_0_1px_rgba(255,255,255,0.07)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white focus-visible:ring-offset-4 focus-visible:ring-offset-[#0b0b0d]\"\n      >\n        {/* The still version: the print, and the second picture through a round window. Shown with reduced motion or without WebGL. */}\n        <img ref={first} src={looks[0].src} alt={looks[0].alt} crossOrigin=\"anonymous\" width={900} height={1350} className={`absolute inset-0 h-full w-full object-cover ${swapped ? \"lgb-still z-10\" : \"\"}`} />\n        <img ref={second} src={looks[1].src} alt={looks[1].alt} crossOrigin=\"anonymous\" width={900} height={1350} className={`absolute inset-0 h-full w-full object-cover ${swapped ? \"\" : \"lgb-still z-10\"}`} />\n        <span aria-hidden=\"true\" className=\"lgb-ring absolute z-10 block rounded-full shadow-[inset_0_0_0_1px_rgba(255,255,255,0.55),inset_6px_8px_14px_rgba(255,255,255,0.22),8px_12px_22px_rgba(0,0,0,0.45)]\" />\n        <canvas ref={canvas} aria-hidden=\"true\" className={`absolute inset-0 z-20 h-full w-full transition-opacity duration-500 ${live ? \"opacity-100\" : \"opacity-0\"}`} />\n      </button>\n\n      <div className=\"mt-8 flex w-[min(82vw,420px)] items-baseline justify-between gap-4 px-0.5 text-[13px]\">\n        <p className=\"text-zinc-300\">\n          <span className=\"font-semibold text-white\">{under.name}</span>\n          <span className=\"mx-2 text-zinc-500\">over</span>\n          {over.name}\n        </p>\n        <p className=\"text-zinc-400\">Click the print to swap</p>\n      </div>\n    </section>\n  );\n}\n"}]}
