Components52 / 118
Liquid Lens
A blob of liquid glass that follows your cursor over your own text. It magnifies the centre, bends hard at the rim, splits the light into a rainbow fringe and catches a highlight, and it squashes and stretches along the way you move it. Wrap any headline in it, or use the built-in scrolling rows.
WebGLWebGLWorks over any textWorks over any textZero dependenciesZero dependencies60fps60fpsReduced-motion safeReduced-motion safe
Glass over anything you write.
Steer the glass, move fast to squash it
Tweak
LIVELIVEUnder the glass
Your own text
Off shows scrolling rows
#f2f0eb
Scrolling rows
#2b5cff
#ff4d00
1.00
Scene
#0b0b0c
Glass
1.00
1.60
1.00
1.00
#bdd5ff
#ff7326
Usage
Follows your tweaks.
usage.tsx
import { LiquidLens } from "@/components/inreact/liquid-lens";
export function Hero() {
return (
<LiquidLens
className="rounded-3xl px-10 py-24"
>
{/* anything you put here goes under the glass */}
<h1 className="text-7xl font-semibold" style={{ color: "#f2f0eb" }}>
Glass over anything you write.
</h1>
</LiquidLens>
);
}Install with the CLI
TS + Tailwind
npx shadcn@latest add https://inreact.vercel.app/r/liquid-lens.jsonTS + CSS
npx shadcn@latest add https://inreact.vercel.app/r/liquid-lens-css.jsonOr copy the source
No dependencies. Save this as components/inreact/liquid-lens.tsx.
components/inreact/liquid-lens.tsx
"use client";
import { useEffect, useRef, type ReactNode } from "react";
/**
* Liquid Lens: a blob of liquid glass that follows the cursor over your text.
*
* Put any text inside it and the glass refracts exactly that: same words,
* fonts, colours and positions. The glass magnifies the centre, bends hard at
* the rim, splits the light into colour, catches highlights and squashes along
* the way you move it. Leave it alone and it drifts.
*
* <LiquidLens className="py-24">
* <h1 className="text-8xl font-bold">Your headline</h1>
* </LiquidLens>
*
* With no children it shows rows of scrolling words (see `words`).
*
* WebGL 1. Without it your text simply stays as it is. The real text stays in
* the DOM for selection and screen readers. Pauses off-screen; with
* prefers-reduced-motion the type holds still. Props update live.
*/
export interface LiquidLensProps {
/** Your text to put under the glass. Without children, scrolling `words` are shown. */
children?: ReactNode;
/** Scrolling rows (only when there are no children). */
words?: string[];
/** Colour per scrolling row; cycles when there are more rows than colours. */
colors?: string[];
/** Colour behind the text. Defaults to the element's own background, else near-black. */
background?: string;
/** Lens size multiplier. */
size?: number;
/** How much the lens magnifies its centre (1 = none). */
zoom?: number;
/** How hard the rim bends what is under it. */
refraction?: number;
/** Strength of the colour split toward the rim. */
aberration?: number;
/** Tint of the glass body. */
tint?: string;
/** Colour of the light pooled inside the far rim. */
rim?: string;
/** Speed of the scrolling rows. */
speed?: number;
className?: string;
}
const VERT = `attribute vec2 p; varying vec2 vUv;
void main(){ vUv = p * 0.5 + 0.5; gl_Position = vec4(p, 0.0, 1.0); }`;
const FRAG = `
precision highp float;
varying vec2 vUv;
uniform sampler2D uTex;
uniform vec2 uRes; // css px
uniform vec2 uLens; // css px, origin top-left
uniform float uR; // radius, css px
uniform vec2 uVel; // movement per frame, for squash and stretch
uniform float uTime;
uniform float uMag; // centre magnification (1 / zoom)
uniform float uRefract; // rim bend, css px
uniform float uAberr; // colour split, css px
uniform vec3 uTint;
uniform vec3 uRim;
vec3 tex(vec2 p) { return texture2D(uTex, clamp(p, vec2(0.001), vec2(0.999))).rgb; }
void main() {
vec2 px = vec2(vUv.x, 1.0 - vUv.y) * uRes;
vec2 uv = px / uRes;
vec2 d = px - uLens;
// squash and stretch along the direction of travel
float speed = length(uVel);
vec2 dir = speed > 0.001 ? uVel / speed : vec2(1.0, 0.0);
float stretch = 1.0 + clamp(speed * 0.02, 0.0, 0.5);
vec2 local = vec2(dot(d, dir) / stretch, dot(d, vec2(-dir.y, dir.x)) * stretch);
// a slow liquid wobble of the outline
float ang = atan(local.y, local.x);
float wob = 1.0 + 0.035 * sin(ang * 3.0 + uTime * 1.7) + 0.025 * sin(ang * 5.0 - uTime * 2.6);
float R = max(uR * wob, 1.0);
float r = length(local) / R;
vec3 bg = tex(uv);
// soft contact shadow, a little below the glass
float sd = length((d - vec2(0.0, uR * 0.22)) * vec2(1.0, 1.25)) / max(uR, 1.0);
vec3 outside = bg * (1.0 - (1.0 - smoothstep(0.7, 1.45, sd)) * 0.36);
// anti-aliased outline, about 1.25 css px wide
float aa = 1.25 / R;
float inside = 1.0 - smoothstep(1.0 - aa, 1.0, r);
if (inside <= 0.0) {
gl_FragColor = vec4(outside, 1.0);
return;
}
// the glass as a dome: its normal drives every effect below
float rr = min(r, 0.9999);
float z = sqrt(1.0 - rr * rr);
vec2 nxy = d / R;
vec3 N = normalize(vec3(nxy, z));
float edge = 1.0 - z;
vec2 ndir = normalize(nxy + 1e-5);
// magnify toward the centre, bend hard toward the rim, split the light
float mag = mix(uMag, 1.0, edge * edge);
vec2 base = (uLens + d * mag - N.xy * pow(edge, 1.5) * uRefract) / uRes;
vec2 disp = N.xy * pow(edge, 1.5) * uAberr / uRes;
// red bends most, blue least: a rainbow fringe that builds toward the rim
vec3 col = vec3(tex(base - disp * 1.4).r, tex(base - disp * 0.4).g, tex(base + disp * 0.8).b);
// a breath of tint; the bevel only slightly denser, so the glass stays clear
col = mix(col, col * uTint, 0.3);
col *= 1.0 - smoothstep(0.78, 1.0, r) * 0.14;
// the sky reflected along the top at grazing angles (adds light, never darkens)
float fres = pow(edge, 2.2);
float sky = 1.0 - smoothstep(-0.7, 0.25, N.y);
col += vec3(0.62, 0.7, 0.9) * fres * sky * 0.5 + vec3(0.55, 0.65, 1.0) * fres * 0.18;
// light focused through the glass pools on the side away from the light
vec2 Lxy = normalize(vec2(-0.55, -0.75));
float pool = smoothstep(0.45, 0.95, r) * smoothstep(0.1, 0.95, dot(ndir, -Lxy));
col += uRim * pool * 0.3;
// highlights: a tight hot spot and a broad soft sheen
vec3 H = normalize(normalize(vec3(-0.5, -0.65, 0.75)) + vec3(0.0, 0.0, 1.0));
float nh = max(dot(N, H), 0.0);
col += vec3(1.0) * (pow(nh, 90.0) * 1.1 + pow(nh, 14.0) * 0.12);
// a thin lit edge on the light side, coloured on the far side
float lit = clamp(dot(ndir, Lxy) * 0.5 + 0.5, 0.0, 1.0);
col += mix(uRim * 0.6, vec3(0.95), lit) * smoothstep(0.86, 0.99, r) * 0.32;
gl_FragColor = vec4(mix(outside, col, inside), 1.0);
}`;
const WORDS = ["MOTION", "SHADER", "REACT", "PHYSICS", "GLASS", "KINETIC"];
const COLORS = ["#f2f0eb", "#2b5cff", "#f2f0eb", "#ff4d00", "#f2f0eb", "#2b5cff"];
function hexToRgb(hex: string): [number, number, number] {
const h = hex.replace("#", "");
const n = parseInt(h.length === 3 ? h.replace(/./g, "$&$&") : h, 16);
return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
}
const isReducedMotion = () =>
typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
/** Background colour to paint behind the text: the prop, else the element's own, else near-black. */
function resolveBackground(host: HTMLElement, prop?: string) {
if (prop) return prop;
const c = getComputedStyle(host).backgroundColor;
const m = c.match(/rgba?\(([^)]+)\)/);
if (m) {
const parts = m[1].split(",").map((x) => parseFloat(x));
if (parts.length < 4 || parts[3] > 0) return c;
}
return "#0b0b0c";
}
export function LiquidLens({
children,
words = WORDS,
colors = COLORS,
background,
size = 1,
zoom = 1.6,
refraction = 1,
aberration = 1,
tint = "#bdd5ff",
rim = "#ff7326",
speed = 1,
className,
}: LiquidLensProps) {
const hostRef = useRef<HTMLDivElement>(null);
const contentRef = useRef<HTMLDivElement>(null);
const hasContent = children !== undefined && children !== null && children !== false;
// live settings: read every frame, so tweaks never restart the lens
const live = useRef({ words, colors, background, size, zoom, refraction, aberration, tint, rim, speed });
const dirty = useRef<(() => void) | null>(null);
useEffect(() => {
live.current = { words, colors, background, size, zoom, refraction, aberration, tint, rim, speed };
dirty.current?.();
}, [words, colors, background, size, zoom, refraction, aberration, tint, rim, speed]);
useEffect(() => {
const host = hostRef.current;
if (!host) return;
// stay where the user put it (absolute, fixed...), otherwise anchor the canvas
if (getComputedStyle(host).position === "static") host.style.position = "relative";
const content = contentRef.current;
const canvas = document.createElement("canvas");
canvas.style.cssText = "position:absolute;inset:0;display:block;width:100%;height:100%;pointer-events:none";
canvas.setAttribute("aria-hidden", "true");
host.prepend(canvas);
// the scene beneath the glass, painted in 2D
const scene = document.createElement("canvas");
const sctx = scene.getContext("2d")!;
let w = 1, h = 1, dpr = 1;
let family = getComputedStyle(host).fontFamily || "Arial";
/* ---------- scene: scrolling rows ---------- */
const drawRows = (t: number) => {
const L = live.current;
sctx.setTransform(dpr, 0, 0, dpr, 0, 0);
sctx.fillStyle = resolveBackground(host, L.background);
sctx.fillRect(0, 0, w, h);
const size = Math.max(34, h / 5.2);
sctx.font = `800 ${size}px ${family}`;
sctx.textBaseline = "middle";
const rows = L.words.length ? L.words : [" "];
for (let i = 0; i < rows.length; i++) {
const y = (i + 0.5) * size * 0.92 - size * 0.2;
const word = `${rows[i]} — `;
const ww = Math.max(1, sctx.measureText(word).width);
const dir = i % 2 ? 1 : -1;
let x = ((t * 40 * dir + i * 137) % ww) - ww;
sctx.fillStyle = L.colors[i % Math.max(1, L.colors.length)] ?? "#f2f0eb";
sctx.globalAlpha = i % 2 ? 0.95 : 0.85;
while (x < w) {
sctx.fillText(word, x, y);
x += ww;
}
}
sctx.globalAlpha = 1;
};
/* ---------- scene: your own text, word for word ---------- */
type Run = { s: string; x: number; y: number; font: string; ls: string; color: string };
let runs: Run[] = [];
let maxFont = 0; // largest font size under the glass, sizes the lens to the type
const layoutContent = () => {
if (!content) return;
const hr = host.getBoundingClientRect();
runs = [];
maxFont = 0;
const walker = document.createTreeWalker(content, NodeFilter.SHOW_TEXT);
const range = document.createRange();
const ascents = new Map<string, number>();
let node: Node | null;
while ((node = walker.nextNode())) {
const raw = node.textContent ?? "";
const parent = node.parentElement;
if (!parent || !raw.trim()) continue;
const cs = getComputedStyle(parent);
// (ancestors may be briefly hidden by an entrance fade: still capture the words)
if (cs.display === "none") continue;
const font = `${cs.fontStyle} ${cs.fontWeight} ${cs.fontSize} ${cs.fontFamily}`;
if (!ascents.has(font)) {
sctx.font = font;
ascents.set(font, sctx.measureText("Hg").fontBoundingBoxAscent);
}
maxFont = Math.max(maxFont, parseFloat(cs.fontSize) || 0);
const tt = cs.textTransform;
const re = /\S+/g;
let m: RegExpExecArray | null;
while ((m = re.exec(raw))) {
range.setStart(node, m.index);
range.setEnd(node, m.index + m[0].length);
const rect = range.getClientRects()[0];
if (!rect) continue;
const s = tt === "uppercase" ? m[0].toUpperCase() : tt === "lowercase" ? m[0].toLowerCase() : m[0];
runs.push({ s, x: rect.left - hr.left, y: rect.top - hr.top + (ascents.get(font) ?? rect.height * 0.8), font, ls: cs.letterSpacing, color: cs.color });
}
}
};
const drawContent = () => {
const L = live.current;
sctx.setTransform(dpr, 0, 0, dpr, 0, 0);
sctx.fillStyle = resolveBackground(host, L.background);
sctx.fillRect(0, 0, w, h);
sctx.textBaseline = "alphabetic";
for (const run of runs) {
sctx.font = run.font;
(sctx as CanvasRenderingContext2D & { letterSpacing: string }).letterSpacing = run.ls;
sctx.fillStyle = run.color;
sctx.fillText(run.s, run.x, run.y);
}
(sctx as CanvasRenderingContext2D & { letterSpacing: string }).letterSpacing = "0px";
};
const gl = canvas.getContext("webgl", { antialias: false, alpha: false, premultipliedAlpha: false });
if (!gl) {
// no WebGL: your text stays as it is; scrolling rows are shown still
canvas.remove();
if (hasContent) return;
scene.style.cssText = "position:absolute;inset:0;display:block;width:100%;height:100%";
scene.setAttribute("aria-hidden", "true");
host.prepend(scene);
const paint = () => {
dpr = Math.min(window.devicePixelRatio || 1, 2);
w = Math.max(1, host.clientWidth);
h = Math.max(1, host.clientHeight);
scene.width = Math.round(w * dpr);
scene.height = Math.round(h * dpr);
drawRows(0);
};
paint();
const ro = new ResizeObserver(paint);
ro.observe(host);
return () => {
ro.disconnect();
scene.remove();
};
}
const mk = (type: number, src: string) => {
const s = gl.createShader(type)!;
gl.shaderSource(s, src);
gl.compileShader(s);
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) console.warn(gl.getShaderInfoLog(s));
return s;
};
const prog = gl.createProgram()!;
gl.attachShader(prog, mk(gl.VERTEX_SHADER, VERT));
gl.attachShader(prog, mk(gl.FRAGMENT_SHADER, FRAG));
gl.linkProgram(prog);
gl.useProgram(prog);
const buf = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buf);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);
const loc = gl.getAttribLocation(prog, "p");
gl.enableVertexAttribArray(loc);
gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0);
const u = (n: string) => gl.getUniformLocation(prog, n);
const U = {
res: u("uRes"), lens: u("uLens"), r: u("uR"), vel: u("uVel"), time: u("uTime"),
mag: u("uMag"), refract: u("uRefract"), aberr: u("uAberr"), tint: u("uTint"), rim: u("uRim"),
};
const tex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex);
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);
// your text is static: paint and upload it only when something changes
let sceneDirty = true;
const markDirty = () => {
sceneDirty = true;
if (!raf) render();
};
dirty.current = markDirty;
const resize = () => {
dpr = Math.min(window.devicePixelRatio || 1, 2);
w = Math.max(1, host.clientWidth);
h = Math.max(1, host.clientHeight);
canvas.width = scene.width = Math.round(w * dpr);
canvas.height = scene.height = Math.round(h * dpr);
gl.viewport(0, 0, canvas.width, canvas.height);
layoutContent();
sceneDirty = true;
};
resize();
const ro = new ResizeObserver(() => {
resize();
if (!raf) render();
});
ro.observe(host);
if (content) ro.observe(content);
// re-lay the words when the text changes or fonts arrive
let mo: MutationObserver | null = null;
if (content) {
mo = new MutationObserver(() => {
layoutContent();
markDirty();
});
mo.observe(content, { childList: true, subtree: true, characterData: true, attributes: true });
}
document.fonts?.ready.then(() => {
family = getComputedStyle(host).fontFamily || "Arial";
layoutContent();
markDirty();
});
const reduced = isReducedMotion();
const st = { x: w * 0.5, y: h * 0.42, tx: w * 0.5, ty: h * 0.42, vx: 0, vy: 0, hover: false, r: 0, rv: 0, t: 0 };
const move = (e: PointerEvent) => {
const r = host.getBoundingClientRect();
st.tx = e.clientX - r.left;
st.ty = e.clientY - r.top;
st.hover = true;
};
const leave = () => (st.hover = false);
host.addEventListener("pointermove", move);
host.addEventListener("pointerleave", leave);
let contentHidden = false;
const render = () => {
const L = live.current;
if (!hasContent) {
drawRows(st.t * L.speed);
sceneDirty = true;
} else if (sceneDirty) {
drawContent();
}
gl.bindTexture(gl.TEXTURE_2D, tex);
if (sceneDirty) {
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, scene);
sceneDirty = false;
// the glass now paints your words: hide the DOM copy (still selectable and read aloud)
if (hasContent && content && !contentHidden) {
content.style.opacity = "0";
contentHidden = true;
}
}
gl.uniform2f(U.res, w, h);
gl.uniform2f(U.lens, st.x, st.y);
gl.uniform1f(U.r, Math.max(0, st.r));
gl.uniform2f(U.vel, st.vx, st.vy);
gl.uniform1f(U.time, st.t);
gl.uniform1f(U.mag, 1 / Math.max(1, L.zoom));
// both scale with the lens, so a big lens bends as much as a small one, proportionally
gl.uniform1f(U.refract, Math.max(0, st.r) * 0.28 * L.refraction);
gl.uniform1f(U.aberr, Math.max(0, st.r) * 0.2 * L.aberration);
const t3 = hexToRgb(L.tint);
gl.uniform3f(U.tint, t3[0] * 1.15, t3[1] * 1.15, t3[2] * 1.15);
gl.uniform3fv(U.rim, hexToRgb(L.rim));
gl.drawArrays(gl.TRIANGLES, 0, 3);
};
let raf = 0;
let visible = false;
let last = 0;
const frame = (now: number) => {
raf = requestAnimationFrame(frame);
const dt = last ? Math.min(0.05, (now - last) / 1000) : 1 / 60;
last = now;
const steps = dt * 60;
st.t += reduced ? 0 : dt;
if (!st.hover && !reduced) {
st.tx = w * 0.5 + Math.sin(st.t * 0.6) * w * 0.28;
st.ty = h * 0.4 + Math.sin(st.t * 0.9 + 1) * h * 0.14;
}
const k = 1 - Math.pow(0.82, steps);
const nx = st.x + (st.tx - st.x) * k;
const ny = st.y + (st.ty - st.y) * k;
st.vx += (nx - st.x - st.vx) * 0.35;
st.vy += (ny - st.y - st.vy) * 0.35;
st.x = nx;
st.y = ny;
// the size springs, with a little jelly overshoot
// over your own text the lens is sized to the type (about one letter tall);
// over the scrolling rows it is sized to the panel
const base = hasContent && maxFont ? Math.min(Math.min(w, h) * 0.24, maxFont * 1.05) : Math.min(w, h) * 0.24;
const target = base * (st.hover ? 1.25 : 1) * live.current.size;
if (reduced) st.r = target;
else {
st.rv += (target - st.r) * 0.08 * steps;
st.rv *= Math.pow(0.8, steps);
st.r += st.rv * steps;
}
render();
};
const sync = () => {
const run = visible && !document.hidden;
if (run && !raf) {
last = 0;
raf = requestAnimationFrame(frame);
} else if (!run && raf) {
cancelAnimationFrame(raf);
raf = 0;
}
};
const io = new IntersectionObserver(([e]) => {
visible = e.isIntersecting;
sync();
});
io.observe(host);
document.addEventListener("visibilitychange", sync);
return () => {
dirty.current = null;
cancelAnimationFrame(raf);
io.disconnect();
ro.disconnect();
mo?.disconnect();
document.removeEventListener("visibilitychange", sync);
host.removeEventListener("pointermove", move);
host.removeEventListener("pointerleave", leave);
if (content) content.style.opacity = "";
gl.getExtension("WEBGL_lose_context")?.loseContext();
canvas.remove();
};
}, [hasContent]);
return (
<div
ref={hostRef}
role={hasContent ? undefined : "img"}
aria-label={hasContent ? undefined : `Liquid glass lens over scrolling words: ${words.join(", ")}`}
className={["overflow-hidden", className].filter(Boolean).join(" ")}
>
{hasContent && (
<div ref={contentRef} style={{ position: "relative", zIndex: 1 }}>
{children}
</div>
)}
</div>
);
}
›Plain CSS variant (no Tailwind)
components/inreact/liquid-lens.tsx
"use client";
import { useEffect, useRef, type ReactNode } from "react";
import "./liquid-lens.css";
/**
* Liquid Lens: a blob of liquid glass that follows the cursor over your text.
*
* Put any text inside it and the glass refracts exactly that: same words,
* fonts, colours and positions. The glass magnifies the centre, bends hard at
* the rim, splits the light into colour, catches highlights and squashes along
* the way you move it. Leave it alone and it drifts.
*
* <LiquidLens className="py-24">
* <h1 className="text-8xl font-bold">Your headline</h1>
* </LiquidLens>
*
* With no children it shows rows of scrolling words (see `words`).
*
* WebGL 1. Without it your text simply stays as it is. The real text stays in
* the DOM for selection and screen readers. Pauses off-screen; with
* prefers-reduced-motion the type holds still. Props update live.
*/
export interface LiquidLensProps {
/** Your text to put under the glass. Without children, scrolling `words` are shown. */
children?: ReactNode;
/** Scrolling rows (only when there are no children). */
words?: string[];
/** Colour per scrolling row; cycles when there are more rows than colours. */
colors?: string[];
/** Colour behind the text. Defaults to the element's own background, else near-black. */
background?: string;
/** Lens size multiplier. */
size?: number;
/** How much the lens magnifies its centre (1 = none). */
zoom?: number;
/** How hard the rim bends what is under it. */
refraction?: number;
/** Strength of the colour split toward the rim. */
aberration?: number;
/** Tint of the glass body. */
tint?: string;
/** Colour of the light pooled inside the far rim. */
rim?: string;
/** Speed of the scrolling rows. */
speed?: number;
className?: string;
}
const VERT = `attribute vec2 p; varying vec2 vUv;
void main(){ vUv = p * 0.5 + 0.5; gl_Position = vec4(p, 0.0, 1.0); }`;
const FRAG = `
precision highp float;
varying vec2 vUv;
uniform sampler2D uTex;
uniform vec2 uRes; // css px
uniform vec2 uLens; // css px, origin top-left
uniform float uR; // radius, css px
uniform vec2 uVel; // movement per frame, for squash and stretch
uniform float uTime;
uniform float uMag; // centre magnification (1 / zoom)
uniform float uRefract; // rim bend, css px
uniform float uAberr; // colour split, css px
uniform vec3 uTint;
uniform vec3 uRim;
vec3 tex(vec2 p) { return texture2D(uTex, clamp(p, vec2(0.001), vec2(0.999))).rgb; }
void main() {
vec2 px = vec2(vUv.x, 1.0 - vUv.y) * uRes;
vec2 uv = px / uRes;
vec2 d = px - uLens;
// squash and stretch along the direction of travel
float speed = length(uVel);
vec2 dir = speed > 0.001 ? uVel / speed : vec2(1.0, 0.0);
float stretch = 1.0 + clamp(speed * 0.02, 0.0, 0.5);
vec2 local = vec2(dot(d, dir) / stretch, dot(d, vec2(-dir.y, dir.x)) * stretch);
// a slow liquid wobble of the outline
float ang = atan(local.y, local.x);
float wob = 1.0 + 0.035 * sin(ang * 3.0 + uTime * 1.7) + 0.025 * sin(ang * 5.0 - uTime * 2.6);
float R = max(uR * wob, 1.0);
float r = length(local) / R;
vec3 bg = tex(uv);
// soft contact shadow, a little below the glass
float sd = length((d - vec2(0.0, uR * 0.22)) * vec2(1.0, 1.25)) / max(uR, 1.0);
vec3 outside = bg * (1.0 - (1.0 - smoothstep(0.7, 1.45, sd)) * 0.36);
// anti-aliased outline, about 1.25 css px wide
float aa = 1.25 / R;
float inside = 1.0 - smoothstep(1.0 - aa, 1.0, r);
if (inside <= 0.0) {
gl_FragColor = vec4(outside, 1.0);
return;
}
// the glass as a dome: its normal drives every effect below
float rr = min(r, 0.9999);
float z = sqrt(1.0 - rr * rr);
vec2 nxy = d / R;
vec3 N = normalize(vec3(nxy, z));
float edge = 1.0 - z;
vec2 ndir = normalize(nxy + 1e-5);
// magnify toward the centre, bend hard toward the rim, split the light
float mag = mix(uMag, 1.0, edge * edge);
vec2 base = (uLens + d * mag - N.xy * pow(edge, 1.5) * uRefract) / uRes;
vec2 disp = N.xy * pow(edge, 1.5) * uAberr / uRes;
// red bends most, blue least: a rainbow fringe that builds toward the rim
vec3 col = vec3(tex(base - disp * 1.4).r, tex(base - disp * 0.4).g, tex(base + disp * 0.8).b);
// a breath of tint; the bevel only slightly denser, so the glass stays clear
col = mix(col, col * uTint, 0.3);
col *= 1.0 - smoothstep(0.78, 1.0, r) * 0.14;
// the sky reflected along the top at grazing angles (adds light, never darkens)
float fres = pow(edge, 2.2);
float sky = 1.0 - smoothstep(-0.7, 0.25, N.y);
col += vec3(0.62, 0.7, 0.9) * fres * sky * 0.5 + vec3(0.55, 0.65, 1.0) * fres * 0.18;
// light focused through the glass pools on the side away from the light
vec2 Lxy = normalize(vec2(-0.55, -0.75));
float pool = smoothstep(0.45, 0.95, r) * smoothstep(0.1, 0.95, dot(ndir, -Lxy));
col += uRim * pool * 0.3;
// highlights: a tight hot spot and a broad soft sheen
vec3 H = normalize(normalize(vec3(-0.5, -0.65, 0.75)) + vec3(0.0, 0.0, 1.0));
float nh = max(dot(N, H), 0.0);
col += vec3(1.0) * (pow(nh, 90.0) * 1.1 + pow(nh, 14.0) * 0.12);
// a thin lit edge on the light side, coloured on the far side
float lit = clamp(dot(ndir, Lxy) * 0.5 + 0.5, 0.0, 1.0);
col += mix(uRim * 0.6, vec3(0.95), lit) * smoothstep(0.86, 0.99, r) * 0.32;
gl_FragColor = vec4(mix(outside, col, inside), 1.0);
}`;
const WORDS = ["MOTION", "SHADER", "REACT", "PHYSICS", "GLASS", "KINETIC"];
const COLORS = ["#f2f0eb", "#2b5cff", "#f2f0eb", "#ff4d00", "#f2f0eb", "#2b5cff"];
function hexToRgb(hex: string): [number, number, number] {
const h = hex.replace("#", "");
const n = parseInt(h.length === 3 ? h.replace(/./g, "$&$&") : h, 16);
return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
}
const isReducedMotion = () =>
typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
/** Background colour to paint behind the text: the prop, else the element's own, else near-black. */
function resolveBackground(host: HTMLElement, prop?: string) {
if (prop) return prop;
const c = getComputedStyle(host).backgroundColor;
const m = c.match(/rgba?\(([^)]+)\)/);
if (m) {
const parts = m[1].split(",").map((x) => parseFloat(x));
if (parts.length < 4 || parts[3] > 0) return c;
}
return "#0b0b0c";
}
export function LiquidLens({
children,
words = WORDS,
colors = COLORS,
background,
size = 1,
zoom = 1.6,
refraction = 1,
aberration = 1,
tint = "#bdd5ff",
rim = "#ff7326",
speed = 1,
className,
}: LiquidLensProps) {
const hostRef = useRef<HTMLDivElement>(null);
const contentRef = useRef<HTMLDivElement>(null);
const hasContent = children !== undefined && children !== null && children !== false;
// live settings: read every frame, so tweaks never restart the lens
const live = useRef({ words, colors, background, size, zoom, refraction, aberration, tint, rim, speed });
const dirty = useRef<(() => void) | null>(null);
useEffect(() => {
live.current = { words, colors, background, size, zoom, refraction, aberration, tint, rim, speed };
dirty.current?.();
}, [words, colors, background, size, zoom, refraction, aberration, tint, rim, speed]);
useEffect(() => {
const host = hostRef.current;
if (!host) return;
// stay where the user put it (absolute, fixed...), otherwise anchor the canvas
if (getComputedStyle(host).position === "static") host.style.position = "relative";
const content = contentRef.current;
const canvas = document.createElement("canvas");
canvas.style.cssText = "position:absolute;inset:0;display:block;width:100%;height:100%;pointer-events:none";
canvas.setAttribute("aria-hidden", "true");
host.prepend(canvas);
// the scene beneath the glass, painted in 2D
const scene = document.createElement("canvas");
const sctx = scene.getContext("2d")!;
let w = 1, h = 1, dpr = 1;
let family = getComputedStyle(host).fontFamily || "Arial";
/* ---------- scene: scrolling rows ---------- */
const drawRows = (t: number) => {
const L = live.current;
sctx.setTransform(dpr, 0, 0, dpr, 0, 0);
sctx.fillStyle = resolveBackground(host, L.background);
sctx.fillRect(0, 0, w, h);
const size = Math.max(34, h / 5.2);
sctx.font = `800 ${size}px ${family}`;
sctx.textBaseline = "middle";
const rows = L.words.length ? L.words : [" "];
for (let i = 0; i < rows.length; i++) {
const y = (i + 0.5) * size * 0.92 - size * 0.2;
const word = `${rows[i]} — `;
const ww = Math.max(1, sctx.measureText(word).width);
const dir = i % 2 ? 1 : -1;
let x = ((t * 40 * dir + i * 137) % ww) - ww;
sctx.fillStyle = L.colors[i % Math.max(1, L.colors.length)] ?? "#f2f0eb";
sctx.globalAlpha = i % 2 ? 0.95 : 0.85;
while (x < w) {
sctx.fillText(word, x, y);
x += ww;
}
}
sctx.globalAlpha = 1;
};
/* ---------- scene: your own text, word for word ---------- */
type Run = { s: string; x: number; y: number; font: string; ls: string; color: string };
let runs: Run[] = [];
let maxFont = 0; // largest font size under the glass, sizes the lens to the type
const layoutContent = () => {
if (!content) return;
const hr = host.getBoundingClientRect();
runs = [];
maxFont = 0;
const walker = document.createTreeWalker(content, NodeFilter.SHOW_TEXT);
const range = document.createRange();
const ascents = new Map<string, number>();
let node: Node | null;
while ((node = walker.nextNode())) {
const raw = node.textContent ?? "";
const parent = node.parentElement;
if (!parent || !raw.trim()) continue;
const cs = getComputedStyle(parent);
// (ancestors may be briefly hidden by an entrance fade: still capture the words)
if (cs.display === "none") continue;
const font = `${cs.fontStyle} ${cs.fontWeight} ${cs.fontSize} ${cs.fontFamily}`;
if (!ascents.has(font)) {
sctx.font = font;
ascents.set(font, sctx.measureText("Hg").fontBoundingBoxAscent);
}
maxFont = Math.max(maxFont, parseFloat(cs.fontSize) || 0);
const tt = cs.textTransform;
const re = /\S+/g;
let m: RegExpExecArray | null;
while ((m = re.exec(raw))) {
range.setStart(node, m.index);
range.setEnd(node, m.index + m[0].length);
const rect = range.getClientRects()[0];
if (!rect) continue;
const s = tt === "uppercase" ? m[0].toUpperCase() : tt === "lowercase" ? m[0].toLowerCase() : m[0];
runs.push({ s, x: rect.left - hr.left, y: rect.top - hr.top + (ascents.get(font) ?? rect.height * 0.8), font, ls: cs.letterSpacing, color: cs.color });
}
}
};
const drawContent = () => {
const L = live.current;
sctx.setTransform(dpr, 0, 0, dpr, 0, 0);
sctx.fillStyle = resolveBackground(host, L.background);
sctx.fillRect(0, 0, w, h);
sctx.textBaseline = "alphabetic";
for (const run of runs) {
sctx.font = run.font;
(sctx as CanvasRenderingContext2D & { letterSpacing: string }).letterSpacing = run.ls;
sctx.fillStyle = run.color;
sctx.fillText(run.s, run.x, run.y);
}
(sctx as CanvasRenderingContext2D & { letterSpacing: string }).letterSpacing = "0px";
};
const gl = canvas.getContext("webgl", { antialias: false, alpha: false, premultipliedAlpha: false });
if (!gl) {
// no WebGL: your text stays as it is; scrolling rows are shown still
canvas.remove();
if (hasContent) return;
scene.style.cssText = "position:absolute;inset:0;display:block;width:100%;height:100%";
scene.setAttribute("aria-hidden", "true");
host.prepend(scene);
const paint = () => {
dpr = Math.min(window.devicePixelRatio || 1, 2);
w = Math.max(1, host.clientWidth);
h = Math.max(1, host.clientHeight);
scene.width = Math.round(w * dpr);
scene.height = Math.round(h * dpr);
drawRows(0);
};
paint();
const ro = new ResizeObserver(paint);
ro.observe(host);
return () => {
ro.disconnect();
scene.remove();
};
}
const mk = (type: number, src: string) => {
const s = gl.createShader(type)!;
gl.shaderSource(s, src);
gl.compileShader(s);
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) console.warn(gl.getShaderInfoLog(s));
return s;
};
const prog = gl.createProgram()!;
gl.attachShader(prog, mk(gl.VERTEX_SHADER, VERT));
gl.attachShader(prog, mk(gl.FRAGMENT_SHADER, FRAG));
gl.linkProgram(prog);
gl.useProgram(prog);
const buf = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buf);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);
const loc = gl.getAttribLocation(prog, "p");
gl.enableVertexAttribArray(loc);
gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0);
const u = (n: string) => gl.getUniformLocation(prog, n);
const U = {
res: u("uRes"), lens: u("uLens"), r: u("uR"), vel: u("uVel"), time: u("uTime"),
mag: u("uMag"), refract: u("uRefract"), aberr: u("uAberr"), tint: u("uTint"), rim: u("uRim"),
};
const tex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex);
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);
// your text is static: paint and upload it only when something changes
let sceneDirty = true;
const markDirty = () => {
sceneDirty = true;
if (!raf) render();
};
dirty.current = markDirty;
const resize = () => {
dpr = Math.min(window.devicePixelRatio || 1, 2);
w = Math.max(1, host.clientWidth);
h = Math.max(1, host.clientHeight);
canvas.width = scene.width = Math.round(w * dpr);
canvas.height = scene.height = Math.round(h * dpr);
gl.viewport(0, 0, canvas.width, canvas.height);
layoutContent();
sceneDirty = true;
};
resize();
const ro = new ResizeObserver(() => {
resize();
if (!raf) render();
});
ro.observe(host);
if (content) ro.observe(content);
// re-lay the words when the text changes or fonts arrive
let mo: MutationObserver | null = null;
if (content) {
mo = new MutationObserver(() => {
layoutContent();
markDirty();
});
mo.observe(content, { childList: true, subtree: true, characterData: true, attributes: true });
}
document.fonts?.ready.then(() => {
family = getComputedStyle(host).fontFamily || "Arial";
layoutContent();
markDirty();
});
const reduced = isReducedMotion();
const st = { x: w * 0.5, y: h * 0.42, tx: w * 0.5, ty: h * 0.42, vx: 0, vy: 0, hover: false, r: 0, rv: 0, t: 0 };
const move = (e: PointerEvent) => {
const r = host.getBoundingClientRect();
st.tx = e.clientX - r.left;
st.ty = e.clientY - r.top;
st.hover = true;
};
const leave = () => (st.hover = false);
host.addEventListener("pointermove", move);
host.addEventListener("pointerleave", leave);
let contentHidden = false;
const render = () => {
const L = live.current;
if (!hasContent) {
drawRows(st.t * L.speed);
sceneDirty = true;
} else if (sceneDirty) {
drawContent();
}
gl.bindTexture(gl.TEXTURE_2D, tex);
if (sceneDirty) {
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, scene);
sceneDirty = false;
// the glass now paints your words: hide the DOM copy (still selectable and read aloud)
if (hasContent && content && !contentHidden) {
content.style.opacity = "0";
contentHidden = true;
}
}
gl.uniform2f(U.res, w, h);
gl.uniform2f(U.lens, st.x, st.y);
gl.uniform1f(U.r, Math.max(0, st.r));
gl.uniform2f(U.vel, st.vx, st.vy);
gl.uniform1f(U.time, st.t);
gl.uniform1f(U.mag, 1 / Math.max(1, L.zoom));
// both scale with the lens, so a big lens bends as much as a small one, proportionally
gl.uniform1f(U.refract, Math.max(0, st.r) * 0.28 * L.refraction);
gl.uniform1f(U.aberr, Math.max(0, st.r) * 0.2 * L.aberration);
const t3 = hexToRgb(L.tint);
gl.uniform3f(U.tint, t3[0] * 1.15, t3[1] * 1.15, t3[2] * 1.15);
gl.uniform3fv(U.rim, hexToRgb(L.rim));
gl.drawArrays(gl.TRIANGLES, 0, 3);
};
let raf = 0;
let visible = false;
let last = 0;
const frame = (now: number) => {
raf = requestAnimationFrame(frame);
const dt = last ? Math.min(0.05, (now - last) / 1000) : 1 / 60;
last = now;
const steps = dt * 60;
st.t += reduced ? 0 : dt;
if (!st.hover && !reduced) {
st.tx = w * 0.5 + Math.sin(st.t * 0.6) * w * 0.28;
st.ty = h * 0.4 + Math.sin(st.t * 0.9 + 1) * h * 0.14;
}
const k = 1 - Math.pow(0.82, steps);
const nx = st.x + (st.tx - st.x) * k;
const ny = st.y + (st.ty - st.y) * k;
st.vx += (nx - st.x - st.vx) * 0.35;
st.vy += (ny - st.y - st.vy) * 0.35;
st.x = nx;
st.y = ny;
// the size springs, with a little jelly overshoot
// over your own text the lens is sized to the type (about one letter tall);
// over the scrolling rows it is sized to the panel
const base = hasContent && maxFont ? Math.min(Math.min(w, h) * 0.24, maxFont * 1.05) : Math.min(w, h) * 0.24;
const target = base * (st.hover ? 1.25 : 1) * live.current.size;
if (reduced) st.r = target;
else {
st.rv += (target - st.r) * 0.08 * steps;
st.rv *= Math.pow(0.8, steps);
st.r += st.rv * steps;
}
render();
};
const sync = () => {
const run = visible && !document.hidden;
if (run && !raf) {
last = 0;
raf = requestAnimationFrame(frame);
} else if (!run && raf) {
cancelAnimationFrame(raf);
raf = 0;
}
};
const io = new IntersectionObserver(([e]) => {
visible = e.isIntersecting;
sync();
});
io.observe(host);
document.addEventListener("visibilitychange", sync);
return () => {
dirty.current = null;
cancelAnimationFrame(raf);
io.disconnect();
ro.disconnect();
mo?.disconnect();
document.removeEventListener("visibilitychange", sync);
host.removeEventListener("pointermove", move);
host.removeEventListener("pointerleave", leave);
if (content) content.style.opacity = "";
gl.getExtension("WEBGL_lose_context")?.loseContext();
canvas.remove();
};
}, [hasContent]);
return (
<div
ref={hostRef}
role={hasContent ? undefined : "img"}
aria-label={hasContent ? undefined : `Liquid glass lens over scrolling words: ${words.join(", ")}`}
className={["liquid-lens", className].filter(Boolean).join(" ")}
>
{hasContent && (
<div ref={contentRef} style={{ position: "relative", zIndex: 1 }}>
{children}
</div>
)}
</div>
);
}
components/inreact/liquid-lens.css
.liquid-lens {
overflow: hidden;
}
One prompt, any AI agent
Paste into Claude Code, Codex, Cursor or Windsurf. It carries your tweaks and the full source, so the agent installs it exactly.
Props
12 propschildrenReactNodeYour text, put under the glass word for word: same fonts, colours and positions. The real text stays in the DOM.backgroundstringColour behind the text. Defaults to the element's own background, else near-black.sizenumberLens size multiplier.default 1default 1zoomnumberHow much the lens magnifies its centre. 1 means none.default 1.6default 1.6refractionnumberHow hard the rim bends what is under it.default 1default 1aberrationnumberStrength of the rainbow fringe toward the rim.default 1default 1tintstringTint of the glass body.default "#bdd5ff"default "#bdd5ff"rimstringColour of the light pooled inside the far rim.default "#ff7326"default "#ff7326"wordsstring[]Scrolling rows, used when there are no children.default ["MOTION", "SHADER", …]default ["MOTION", "SHADER", …]colorsstring[]Colour per scrolling row; cycles.default chalk, cobalt, chalk, signal…default chalk, cobalt, chalk, signal…speednumberSpeed of the scrolling rows.default 1default 1classNamestringSize or pad it, e.g. px-10 py-24, or h-[420px] w-full for rows.