labs

liquid glass

2026-09-03
2 px
40
16 px

a map made for the panel

an edge that refracts is a displacement map, and the map has to be generated from the panel's own shape or its ring sits on a corner the panel is not wearing.

refraction and frost

it cannot be one element either: an element carrying a filter is a backdrop root, so its own backdrop-filter samples the filtered copy instead of the page, and no single layer both refracts and frosts. so the refracting layer is a clipped duplicate of the ground, moved by the negative of the panel's offset, and the frost is its sibling.

across browsers

the canonical build puts the map straight on the backdrop, which only chromium does, and safari parses the declaration, reports support and paints nothing. this build refracts the duplicate instead, so it works in both.

take it with you

three steps, and the stage above runs in your own project.

  1. install

    nothing to add. it runs on react alone, 18 or newer.

  2. copy

    4 files, kept together in one folder, liquid-glass/. the styles travel with them.

    "use client";
    
    import { useCallback, useId, useLayoutEffect, useRef, useState, type KeyboardEvent } from "react";
    import { useReducedMotion } from "./motion";
    import { displacementMap, ringMask } from "./displacement";
    import "./liquid-glass.css";
    
    interface Props {
      // the tiles behind the glass, four to a row
      images: string[];
      caption?: string;
      // px of frost behind the glass
      blur?: number;
      // how far the edge bends what is behind it
      strength?: number;
      // px width of the curved rim that does the bending
      bevel?: number;
      refraction?: boolean;
      // true refracts through backdrop-filter instead, which only chromium paints
      backdropRoute?: boolean;
      onGrab?: () => void;
    }
    
    const RADIUS = 26;
    
    const NUDGE = 8;
    
    export default function LiquidGlass({
      images,
      caption = "drag the glass across the covers.",
      blur = 2,
      strength = 40,
      bevel = 16,
      refraction = true,
      backdropRoute = false,
      onGrab,
    }: Props) {
      const filterId = useId().replace(/:/g, "");
      const reduced = useReducedMotion();
    
      const stage = useRef<HTMLDivElement>(null);
      const panel = useRef<HTMLDivElement>(null);
      const copy = useRef<HTMLDivElement>(null);
    
      const [box, setBox] = useState({ stageW: 0, stageH: 0, panelW: 0, panelH: 0 });
      const at = useRef({ x: 0, y: 0 });
      const dragging = useRef(false);
      const grab = useRef({ x: 0, y: 0 });
    
      const place = useCallback((x: number, y: number) => {
        at.current = { x, y };
        if (panel.current) panel.current.style.transform = `translate3d(${x}px, ${y}px, 0)`;
        if (copy.current) copy.current.style.transform = `translate3d(${-x}px, ${-y}px, 0)`;
      }, []);
    
      const clamp = useCallback(
        (x: number, y: number) => ({
          x: Math.min(Math.max(0, x), Math.max(0, box.stageW - box.panelW)),
          y: Math.min(Math.max(0, y), Math.max(0, box.stageH - box.panelH)),
        }),
        [box],
      );
    
      useLayoutEffect(() => {
        const stageEl = stage.current;
        const panelEl = panel.current;
        if (!stageEl || !panelEl) return;
        const measure = () => {
          const s = stageEl.getBoundingClientRect();
          const p = panelEl.getBoundingClientRect();
          setBox({ stageW: s.width, stageH: s.height, panelW: p.width, panelH: p.height });
        };
        measure();
        const observer = new ResizeObserver(measure);
        observer.observe(stageEl);
        observer.observe(panelEl);
        return () => observer.disconnect();
      }, []);
    
      const placed = useRef(false);
      useLayoutEffect(() => {
        if (box.stageW <= 0 || box.panelW <= 0) return;
        if (!placed.current) {
          placed.current = true;
          place((box.stageW - box.panelW) / 2, (box.stageH - box.panelH) / 2);
          return;
        }
        const next = clamp(at.current.x, at.current.y);
        place(next.x, next.y);
      }, [box, clamp, place]);
    
      const onKeyDown = (event: KeyboardEvent) => {
        const by: Record<string, [number, number]> = {
          ArrowLeft: [-NUDGE, 0],
          ArrowRight: [NUDGE, 0],
          ArrowUp: [0, -NUDGE],
          ArrowDown: [0, NUDGE],
        };
        const move = by[event.key];
        if (!move) return;
        event.preventDefault();
        const next = clamp(at.current.x + move[0], at.current.y + move[1]);
        place(next.x, next.y);
      };
    
      const shape = {
        width: box.panelW || 1,
        height: box.panelH || 1,
        radius: RADIUS,
        bevel: bevel,
      };
      const map = displacementMap(shape);
      const rim = ringMask(shape);
    
      const refracting = refraction && !backdropRoute;
      const refractFilter = [blur > 0 ? `blur(${blur}px)` : "", `url(#${filterId})`]
        .filter(Boolean)
        .join(" ");
      const backdropFilter = [
        refraction && backdropRoute ? `url(#${filterId})` : "",
        blur > 0 ? `blur(${blur}px)` : "",
        "saturate(1.35)",
        "brightness(1.05)",
      ]
        .filter(Boolean)
        .join(" ");
    
      return (
        <div className="lg-lab">
          <div className="lg-stage" ref={stage}>
            <Backdrop images={images} caption={caption} />
    
            <div
              className="lg-panel"
              ref={panel}
              tabIndex={0}
              aria-label="glass panel. move it with the arrow keys"
              style={{ borderRadius: RADIUS }}
              onKeyDown={onKeyDown}
              onPointerDown={(event) => {
                onGrab?.();
                dragging.current = true;
                try {
                  event.currentTarget.setPointerCapture(event.pointerId);
                } catch {}
                event.currentTarget.focus({ focusVisible: false });
                grab.current = { x: event.clientX - at.current.x, y: event.clientY - at.current.y };
              }}
              onPointerMove={(event) => {
                if (!dragging.current) return;
                const next = clamp(event.clientX - grab.current.x, event.clientY - grab.current.y);
                place(next.x, next.y);
              }}
              onPointerUp={() => {
                dragging.current = false;
              }}
              onPointerCancel={() => {
                dragging.current = false;
              }}
            >
              <div
                className="lg-frost"
                style={{
                  borderRadius: RADIUS,
                  backdropFilter,
                  WebkitBackdropFilter: backdropFilter,
                }}
                aria-hidden="true"
              />
    
              <div className="lg-clip" style={{ borderRadius: RADIUS }} aria-hidden="true">
                <div
                  className="lg-refract"
                  style={{
                    borderRadius: RADIUS,
                    maskImage: `url("${rim}")`,
                    WebkitMaskImage: `url("${rim}")`,
                    filter: refracting ? refractFilter : undefined,
                    display: backdropRoute ? "none" : undefined,
                  }}
                >
                  <div
                    className="lg-copy"
                    ref={copy}
                    style={box.stageW ? { width: box.stageW, height: box.stageH } : { display: "none" }}
                  >
                    <Backdrop images={images} caption={caption} />
                  </div>
                </div>
              </div>
    
              <div
                className="lg-bevel"
                style={{
                  borderRadius: RADIUS,
                  maskImage: `url("${rim}")`,
                  WebkitMaskImage: `url("${rim}")`,
                }}
                aria-hidden="true"
              />
              <div className="lg-surface" style={{ borderRadius: RADIUS }} aria-hidden="true" />
            </div>
    
            <svg className="lg-defs" aria-hidden="true" focusable="false">
              <filter
                id={filterId}
                x="-25%"
                y="-25%"
                width="150%"
                height="150%"
                colorInterpolationFilters="sRGB"
              >
                <feFlood floodColor="#808080" result="flat" />
                <feImage
                  href={map}
                  x="0"
                  y="0"
                  width={box.panelW || 1}
                  height={box.panelH || 1}
                  preserveAspectRatio="none"
                  result="ring"
                />
                <feComposite in="ring" in2="flat" operator="over" result="map" />
                <feDisplacementMap
                  in="SourceGraphic"
                  in2="map"
                  scale={reduced ? Math.min(strength, 40) : strength}
                  xChannelSelector="R"
                  yChannelSelector="G"
                />
              </filter>
            </svg>
          </div>
        </div>
      );
    }
    
    function Backdrop({ images, caption }: { images: string[]; caption: string }) {
      return (
        <div className="lg-ground">
          <p className="lg-line">{caption}</p>
          <div className="lg-tiles">
            {images.map((src, i) => (
              <span key={`${i}-${src}`} className="lg-tile">
                <img src={src} alt="" draggable={false} />
              </span>
            ))}
          </div>
        </div>
      );
    }
    
  3. use

    the stage above, exactly as it runs here. the comments mark what to change.

    example.tsx
    "use client";
    
    import LiquidGlass from "./liquid-glass/LiquidGlass";
    
    // anything busy works behind the glass; swap these for your own images
    const IMAGES = ["eras", "movievault", "riso", "quizzme", "fandeck", "island", "pasteup", "card"].map(
      (seed) => `https://picsum.photos/seed/${seed}/480/300`,
    );
    
    export default function LiquidGlassExample({
      images = IMAGES,
      blur = 2,
      strength = 40,
      bevel = 16,
      refraction = true,
      backdropRoute = false,
      onGrab,
    }: {
      // the five controls above the stage
      images?: string[];
      blur?: number;
      strength?: number;
      bevel?: number;
      refraction?: boolean;
      backdropRoute?: boolean;
      onGrab?: () => void;
    }) {
      return (
        <LiquidGlass
          images={images}
          blur={blur}
          strength={strength}
          bevel={bevel}
          refraction={refraction}
          backdropRoute={backdropRoute}
          onGrab={onGrab}
        />
      );
    }