Backgrounds01 / 118
Liquid Obsidian
A sheet of black, glossy liquid lit by two hidden studio lights. Your cursor leaves a real wake, a click drops a stone, and a headline can sink under the surface and bend with the ripples while staying readable.
WebGL2WebGL2Zero dependenciesZero dependencies60fps60fpsLive tweaksLive tweaksReduced-motion safeReduced-motion safe
Make waves.
Move through itClick to drop a stone
Tweak
LIVELIVELight
#ff4d00
#2b5cff
Surface
1.00
0.980
1.6
Headline
Sink the headline
Text bends under the surface
10px
Usage
Follows your tweaks.
usage.tsx
import { LiquidObsidian } from "@/components/inreact/liquid-obsidian";
export function Hero() {
return (
<section className="relative isolate grid min-h-[80vh] place-items-center overflow-hidden">
<LiquidObsidian className="absolute inset-0 -z-10" text="[data-sink]" />
<h2 data-sink className="text-6xl font-medium text-white">Make waves.</h2>
</section>
);
}Install with the CLI
TS + Tailwind
npx shadcn@latest add https://inreact.vercel.app/r/liquid-obsidian.jsonTS + CSS
npx shadcn@latest add https://inreact.vercel.app/r/liquid-obsidian-css.jsonOr copy the source
No dependencies. Save this as components/inreact/liquid-obsidian.tsx.
components/inreact/liquid-obsidian.tsx
"use client";
import { useEffect, useRef } from "react";
/**
* Liquid Obsidian: the background becomes a sheet of black, glossy liquid
* lit by hidden studio lights.
*
* - At rest it is almost pure black; stray droplets send soft rings across it.
* - The cursor drags through the surface and leaves a real wake (a GPU wave
* simulation). The waves bend the light, so ripples flash with the light
* colours across the black.
* - Click drops a stone: a ring wave crosses the whole section and reflects
* off the edges.
* - Optional: sink a headline under the surface so the ripples bend it.
*
* Usage: place it as the first child of a positioned section.
*
* <section className="relative isolate overflow-hidden">
* <LiquidObsidian className="absolute inset-0 -z-10" text="[data-sink]" />
* <h2 data-sink>Make waves.</h2>
* </section>
*
* Needs WebGL2 with float render targets; otherwise it falls back to a still,
* lit-liquid gradient and leaves the text untouched. Pauses off-screen and
* honours prefers-reduced-motion. Colours and sliders update live, without
* restarting the simulation.
*/
export interface LiquidObsidianProps {
className?: string;
/** First studio light (top-left). */
lightA?: string;
/** Second studio light (bottom-right). */
lightB?: string;
/** How long ripples live: 0.95 (short) to 0.995 (long). */
damping?: number;
/** Brightness of the reflections. */
intensity?: number;
/** Ambient droplets per second (0 to turn off). */
rain?: number;
/**
* CSS selector (searched inside the parent element) of text to sink under
* the surface. It is redrawn inside the liquid and bends with the ripples,
* while the real DOM text stays in place, invisible, for selection and
* screen readers. Per-word opacity (e.g. a scroll reveal) is mirrored.
*/
text?: string;
/** How far ripples bend the submerged text, in CSS px. */
refraction?: number;
}
const VERT = `#version 300 es
in vec2 p;
out vec2 vUv;
void main() {
vUv = p * 0.5 + 0.5;
gl_Position = vec4(p, 0.0, 1.0);
}`;
/* Wave equation on a height field. r = height now, g = height last step. */
const SIM = `#version 300 es
precision highp float;
uniform sampler2D uState;
uniform vec2 uTexel;
uniform vec2 uSize;
uniform vec2 uA;
uniform vec2 uB;
uniform float uForce;
uniform float uRadius;
uniform vec4 uDrop;
uniform float uDamp;
in vec2 vUv;
out vec4 o;
float capsule(vec2 p, vec2 a, vec2 b) {
vec2 pa = p - a, ba = b - a;
float h = clamp(dot(pa, ba) / max(dot(ba, ba), 1e-4), 0.0, 1.0);
return length(pa - ba * h);
}
void main() {
vec4 s = texture(uState, vUv);
float l = texture(uState, vUv - vec2(uTexel.x, 0.0)).r;
float r = texture(uState, vUv + vec2(uTexel.x, 0.0)).r;
float d = texture(uState, vUv - vec2(0.0, uTexel.y)).r;
float u = texture(uState, vUv + vec2(0.0, uTexel.y)).r;
float h = (l + r + d + u) * 0.5 - s.g;
h *= uDamp;
vec2 p = vUv * uSize;
float dc = capsule(p, uA, uB);
h -= uForce * exp(-dc * dc / (uRadius * uRadius));
float dd = length(p - uDrop.xy);
h -= uDrop.w * exp(-dd * dd / (uDrop.z * uDrop.z));
o = vec4(clamp(h, -8.0, 8.0), s.r, 0.0, 1.0);
}`;
/* Shade the surface: normals from the height field, reflected into two soft
coloured lights and a thin white key light. Flat liquid stays black.
Optional submerged text is refracted through the surface. */
const RENDER = `#version 300 es
precision highp float;
uniform sampler2D uState;
uniform sampler2D uText;
uniform vec2 uTexel;
uniform vec3 uLightA;
uniform vec3 uLightB;
uniform float uIntensity;
uniform float uAspect;
uniform vec4 uGuard;
uniform vec4 uTextBox;
uniform float uHasText;
uniform vec2 uRefract;
in vec2 vUv;
out vec4 o;
void main() {
float hl = texture(uState, vUv - vec2(uTexel.x, 0.0)).r;
float hr = texture(uState, vUv + vec2(uTexel.x, 0.0)).r;
float hd = texture(uState, vUv - vec2(0.0, uTexel.y)).r;
float hu = texture(uState, vUv + vec2(0.0, uTexel.y)).r;
vec3 n = normalize(vec3((hl - hr) * 3.2, (hd - hu) * 3.2, 1.0));
vec3 R = reflect(vec3(0.0, 0.0, -1.0), n);
// light directions drift slightly across the section for a studio feel
vec2 q = vUv - 0.5;
q.x *= uAspect;
vec3 La = normalize(vec3(-0.55 - q.x * 0.25, 0.55 - q.y * 0.25, 0.62));
vec3 Lb = normalize(vec3(0.6 - q.x * 0.25, -0.45 - q.y * 0.25, 0.66));
vec3 Lk = normalize(vec3(0.05, 0.75, 0.66));
float sa = pow(max(dot(R, La), 0.0), 26.0);
float sb = pow(max(dot(R, Lb), 0.0), 26.0);
float sk = pow(max(dot(R, Lk), 0.0), 160.0);
float slope = length(n.xy);
vec3 spec = (uLightA * sa * 1.6 + uLightB * sb * 1.9 + vec3(1.0, 0.98, 0.95) * sk * 1.1) * uIntensity;
vec3 col = vec3(0.006) + spec + vec3(0.05, 0.05, 0.06) * smoothstep(0.0, 0.6, slope) * uIntensity;
// calmer reflections around the headline so the words always win
vec2 gp = vec2(vUv.x, 1.0 - vUv.y);
vec2 gd = max(uGuard.xy - gp, gp - uGuard.zw);
float inGuard = 1.0 - smoothstep(0.0, 0.08, max(gd.x, gd.y));
col *= 1.0 - 0.5 * inGuard;
// melt into the page at the top and bottom
float fade = smoothstep(0.0, 0.12, vUv.y) * smoothstep(1.0, 0.88, vUv.y);
col *= fade;
// a whisper of filmic roll-off so hot glints stay rich, not clipped
col = col / (1.0 + col * 0.25);
if (uHasText > 0.5) {
// the text lies under the surface: ripples bend it, with a hair of dispersion
vec2 tb = uTextBox.zw - uTextBox.xy;
vec2 tuv = (vUv - uTextBox.xy) / tb;
// bend, but never so far that a word stops reading: cap the offset
vec2 bend = n.xy;
float bl = length(bend);
bend *= min(1.0, 0.45 / max(bl, 1e-4));
vec2 off = (bend * uRefract) / tb;
vec4 tr = texture(uText, tuv + off * 1.1);
vec4 tg = texture(uText, tuv + off);
vec4 tbl = texture(uText, tuv + off * 0.9);
vec3 trgb = vec3(tr.r, tg.g, tbl.b);
float ta = max(tg.a, max(tr.a, tbl.a));
// light gathered by the moving surface brightens the letters (caustics)
trgb *= 1.0 + smoothstep(0.02, 0.5, slope) * 0.45;
col = col * (1.0 - ta) + trgb;
// the surface sits above the words: its glints slide across them
vec3 glint = spec * 0.45 * ta * fade;
col += glint / (1.0 + glint);
}
o = vec4(col, 1.0);
}`;
const isReducedMotion = () =>
typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
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];
}
function program(gl: WebGL2RenderingContext, vsSrc: string, fsSrc: string) {
const make = (type: number, src: string) => {
const s = gl.createShader(type)!;
gl.shaderSource(s, src);
gl.compileShader(s);
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {
console.error(gl.getShaderInfoLog(s));
return null;
}
return s;
};
const vs = make(gl.VERTEX_SHADER, vsSrc);
const fs = make(gl.FRAGMENT_SHADER, fsSrc);
if (!vs || !fs) return null;
const p = gl.createProgram()!;
gl.attachShader(p, vs);
gl.attachShader(p, fs);
gl.bindAttribLocation(p, 0, "p");
gl.linkProgram(p);
if (!gl.getProgramParameter(p, gl.LINK_STATUS)) {
console.error(gl.getProgramInfoLog(p));
return null;
}
return p;
}
export function LiquidObsidian({
className,
lightA = "#ff4d00",
lightB = "#2b5cff",
damping = 0.98,
intensity = 1,
rain = 1.6,
text,
refraction = 10,
}: LiquidObsidianProps) {
const hostRef = useRef<HTMLDivElement>(null);
// live settings: read every frame, so tweaks never restart the simulation
const live = useRef({ lightA, lightB, damping, intensity, rain, refraction });
const redraw = useRef<(() => void) | null>(null);
useEffect(() => {
live.current = { lightA, lightB, damping, intensity, rain, refraction };
redraw.current?.();
}, [lightA, lightB, damping, intensity, rain, refraction]);
useEffect(() => {
const host = hostRef.current;
if (!host) return;
const canvas = document.createElement("canvas");
canvas.setAttribute("aria-hidden", "true");
canvas.style.cssText = "display:block;width:100%;height:100%";
host.appendChild(canvas);
const gl = canvas.getContext("webgl2", { antialias: false, alpha: false, depth: false, stencil: false });
const floatOk = !!gl && !!gl.getExtension("EXT_color_buffer_float");
if (!gl || !floatOk) {
// no float render targets: keep a still, lit-liquid look
canvas.remove();
host.style.background =
"radial-gradient(60% 50% at 18% 30%, rgba(255,77,0,0.10), transparent 70%), radial-gradient(55% 45% at 85% 75%, rgba(43,92,255,0.12), transparent 70%), #000";
return;
}
const simProg = program(gl, VERT, SIM);
const renProg = program(gl, VERT, RENDER);
if (!simProg || !renProg) return;
const vao = gl.createVertexArray();
gl.bindVertexArray(vao);
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);
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
const S = (n: string) => gl.getUniformLocation(simProg, n);
const Rn = (n: string) => gl.getUniformLocation(renProg, n);
const su = {
state: S("uState"),
texel: S("uTexel"),
size: S("uSize"),
a: S("uA"),
b: S("uB"),
force: S("uForce"),
radius: S("uRadius"),
drop: S("uDrop"),
damp: S("uDamp"),
};
const ru = {
state: Rn("uState"),
texel: Rn("uTexel"),
la: Rn("uLightA"),
lb: Rn("uLightB"),
intensity: Rn("uIntensity"),
aspect: Rn("uAspect"),
guard: Rn("uGuard"),
text: Rn("uText"),
textBox: Rn("uTextBox"),
hasText: Rn("uHasText"),
refract: Rn("uRefract"),
};
/* ---------- ping-pong height field ---------- */
type Target = { tex: WebGLTexture; fbo: WebGLFramebuffer };
let targets: Target[] = [];
let cur = 0;
let sw = 1;
let sh = 1;
let w = 1;
let h = 1;
let simScale = 0.25;
const makeTarget = (): Target => {
const tex = gl.createTexture()!;
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA16F, sw, sh, 0, gl.RGBA, gl.HALF_FLOAT, null);
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);
const fbo = gl.createFramebuffer()!;
gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
gl.clearColor(0, 0, 0, 1);
gl.clear(gl.COLOR_BUFFER_BIT);
return { tex, fbo };
};
const resize = () => {
w = Math.max(1, host.clientWidth);
h = Math.max(1, host.clientHeight);
const dpr = Math.min(window.devicePixelRatio || 1, 1.5);
canvas.width = Math.round(w * dpr);
canvas.height = Math.round(h * dpr);
// ~4 css px per simulation cell; coarser on small screens
simScale = w < 768 ? 0.2 : 0.25;
sw = Math.max(32, Math.round(w * simScale));
sh = Math.max(32, Math.round(h * simScale));
targets.forEach((t) => {
gl.deleteTexture(t.tex);
gl.deleteFramebuffer(t.fbo);
});
targets = [makeTarget(), makeTarget()];
cur = 0;
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
};
resize();
/* ---------- input ---------- */
const ptr = { cx: -1, cy: -1, has: false, sx: 0, sy: 0, psx: 0, psy: 0, primed: false };
let drop: { x: number; y: number; r: number; s: number } | null = null;
const onMove = (e: PointerEvent) => {
ptr.cx = e.clientX;
ptr.cy = e.clientY;
ptr.has = true;
};
const onDown = (e: PointerEvent) => {
const r = host.getBoundingClientRect();
const x = e.clientX - r.left;
const y = e.clientY - r.top;
if (x < 0 || y < 0 || x > r.width || y > r.height) return;
drop = { x: x * simScale, y: (h - y) * simScale, r: 10, s: 1.9 };
};
const onOut = (e: PointerEvent) => {
if (!e.relatedTarget) ptr.has = false;
};
window.addEventListener("pointermove", onMove, { passive: true });
window.addEventListener("pointerdown", onDown, { passive: true });
document.addEventListener("pointerout", onOut);
/* ---------- submerged text ---------- */
const textEl = text ? (host.parentElement?.querySelector(text) as HTMLElement | null) : null;
const tcan = document.createElement("canvas");
const tctx = tcan.getContext("2d")!;
const textTex = gl.createTexture()!;
gl.bindTexture(gl.TEXTURE_2D, textTex);
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);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(4));
type Run = { s: string; x: number; y: number; font: string; ls: string; color: string; chain: HTMLElement[] };
let runs: Run[] = [];
let ops: number[] = [];
let textReady = false;
const MARGIN = 40;
let box = { x: 0, y: 0, w: 1, h: 1 };
let guardBox: [number, number, number, number] = [2, 2, -1, -1];
const layoutText = () => {
if (!textEl) return;
const hr = host.getBoundingClientRect();
const er = textEl.getBoundingClientRect();
guardBox = [
(er.left - hr.left) / hr.width,
(er.top - hr.top) / hr.height,
(er.right - hr.left) / hr.width,
(er.bottom - hr.top) / hr.height,
];
box = { x: er.left - hr.left - MARGIN, y: er.top - hr.top - MARGIN, w: er.width + MARGIN * 2, h: er.height + MARGIN * 2 };
const tdpr = Math.min(window.devicePixelRatio || 1, 2);
tcan.width = Math.max(1, Math.round(box.w * tdpr));
tcan.height = Math.max(1, Math.round(box.h * tdpr));
tctx.setTransform(tdpr, 0, 0, tdpr, 0, 0);
runs = [];
const walker = document.createTreeWalker(textEl, NodeFilter.SHOW_TEXT);
const range = document.createRange();
const ascents = new Map<string, number>();
let node: Node | null;
while ((node = walker.nextNode())) {
const str = node.textContent ?? "";
const parent = node.parentElement;
if (!parent || !str.trim()) continue;
const cs = getComputedStyle(parent);
const font = `${cs.fontStyle} ${cs.fontWeight} ${cs.fontSize} ${cs.fontFamily}`;
if (!ascents.has(font)) {
tctx.font = font;
ascents.set(font, tctx.measureText("Hg").fontBoundingBoxAscent);
}
const chain: HTMLElement[] = [];
for (let e: HTMLElement | null = parent; e && e !== textEl; e = e.parentElement) chain.push(e);
const re = /\S+/g;
let m: RegExpExecArray | null;
while ((m = re.exec(str))) {
range.setStart(node, m.index);
range.setEnd(node, m.index + m[0].length);
const rect = range.getClientRects()[0];
if (!rect) continue;
runs.push({
s: m[0],
x: rect.left - hr.left - box.x,
y: rect.top - hr.top - box.y + (ascents.get(font) ?? rect.height * 0.8),
font,
ls: cs.letterSpacing,
color: cs.color,
chain,
});
}
}
ops = runs.map(() => -1);
};
// redraw the words only when their reveal opacity actually changes
const syncText = () => {
if (!textEl || !runs.length) return;
let dirty = false;
for (let i = 0; i < runs.length; i++) {
let op = 1;
for (const e of runs[i].chain) {
const v = e.style.opacity;
if (v) op *= parseFloat(v);
}
op = Math.round(op * 48) / 48;
if (op !== ops[i]) {
ops[i] = op;
dirty = true;
}
}
if (!dirty) return;
tctx.clearRect(0, 0, box.w, box.h);
for (let i = 0; i < runs.length; i++) {
const run = runs[i];
if (ops[i] <= 0) continue;
tctx.globalAlpha = ops[i];
tctx.font = run.font;
(tctx as CanvasRenderingContext2D & { letterSpacing: string }).letterSpacing = run.ls;
tctx.fillStyle = run.color;
tctx.fillText(run.s, run.x, run.y);
}
tctx.globalAlpha = 1;
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_2D, textTex);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, tcan);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
if (!textReady) {
// the liquid now draws the words: hide the DOM copy (still selectable and read aloud)
textReady = true;
textEl.style.opacity = "0";
}
};
/* ---------- passes ---------- */
const simulate = (force: number, ax: number, ay: number, bx: number, by: number, d: typeof drop) => {
const src = targets[cur];
const dst = targets[1 - cur];
gl.useProgram(simProg);
gl.bindFramebuffer(gl.FRAMEBUFFER, dst.fbo);
gl.viewport(0, 0, sw, sh);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, src.tex);
gl.uniform1i(su.state, 0);
gl.uniform2f(su.texel, 1 / sw, 1 / sh);
gl.uniform2f(su.size, sw, sh);
gl.uniform2f(su.a, ax, ay);
gl.uniform2f(su.b, bx, by);
gl.uniform1f(su.force, force);
gl.uniform1f(su.radius, 3.2);
gl.uniform4f(su.drop, d ? d.x : -999, d ? d.y : -999, d ? d.r : 1, d ? d.s : 0);
gl.uniform1f(su.damp, Math.sqrt(live.current.damping));
gl.drawArrays(gl.TRIANGLES, 0, 3);
cur = 1 - cur;
};
const render = () => {
const L = live.current;
gl.useProgram(renProg);
gl.uniform3fv(ru.la, hexToRgb(L.lightA));
gl.uniform3fv(ru.lb, hexToRgb(L.lightB));
gl.uniform1f(ru.intensity, L.intensity);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.viewport(0, 0, canvas.width, canvas.height);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, targets[cur].tex);
gl.uniform1i(ru.state, 0);
gl.uniform2f(ru.texel, 1 / sw, 1 / sh);
gl.uniform1f(ru.aspect, w / h);
gl.uniform4f(ru.guard, guardBox[0], guardBox[1], guardBox[2], guardBox[3]);
syncText();
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_2D, textTex);
gl.uniform1i(ru.text, 1);
gl.uniform1f(ru.hasText, textReady ? 1 : 0);
// text box in surface uv space (origin bottom-left)
gl.uniform4f(ru.textBox, box.x / w, 1 - (box.y + box.h) / h, (box.x + box.w) / w, 1 - box.y / h);
gl.uniform2f(ru.refract, L.refraction / w, L.refraction / h);
gl.drawArrays(gl.TRIANGLES, 0, 3);
};
/* ---------- loop ---------- */
const reduced = isReducedMotion();
let rainClock = 0;
let acc = 0;
const STEP = 1 / 60;
const tick = (dt: number) => {
const r = host.getBoundingClientRect();
const inside = ptr.has && ptr.cx >= r.left && ptr.cx <= r.right && ptr.cy >= r.top && ptr.cy <= r.bottom;
// pointer in simulation space (origin bottom-left)
const sx = (ptr.cx - r.left) * simScale;
const sy = (h - (ptr.cy - r.top)) * simScale;
if (inside && !ptr.primed) {
ptr.psx = sx;
ptr.psy = sy;
ptr.primed = true;
}
if (!inside) ptr.primed = false;
// fixed-step physics so the waves behave the same on 60/120/144 Hz screens
acc = Math.min(acc + dt, STEP * 4);
const steps = Math.floor(acc / STEP);
acc -= steps * STEP;
for (let k = 0; k < steps; k++) {
let force = 0;
let ax = -999;
let ay = -999;
let bx = -999;
let by = -999;
if (inside) {
// walk the segment from last to current position across the steps
const t0 = k / steps;
const t1 = (k + 1) / steps;
ax = ptr.psx + (sx - ptr.psx) * t0;
ay = ptr.psy + (sy - ptr.psy) * t0;
bx = ptr.psx + (sx - ptr.psx) * t1;
by = ptr.psy + (sy - ptr.psy) * t1;
const moved = Math.hypot(bx - ax, by - ay);
force = Math.min(0.55, moved * 0.09);
}
let d: typeof drop = null;
if (k === 0 && drop) {
d = drop;
drop = null;
} else if (live.current.rain > 0) {
rainClock += STEP;
if (rainClock > 1 / live.current.rain) {
rainClock = 0;
d = { x: Math.random() * sw, y: sh * (0.15 + Math.random() * 0.7), r: 2.6 + Math.random() * 2.2, s: 0.55 + Math.random() * 0.45 };
}
}
// two wave sub-steps per physics step: ripples travel twice as fast
simulate(force, ax, ay, bx, by, d);
simulate(0, -999, -999, -999, -999, null);
}
if (inside) {
ptr.psx = sx;
ptr.psy = sy;
}
render();
};
let raf = 0;
let visible = false;
let last = 0;
const frame = (now: number) => {
raf = requestAnimationFrame(frame);
const dt = last ? Math.min(0.1, (now - last) / 1000) : STEP;
last = now;
tick(dt);
};
const sync = () => {
const go = visible && !document.hidden && !reduced;
if (go && !raf) {
last = 0;
raf = requestAnimationFrame(frame);
} else if (!go && raf) {
cancelAnimationFrame(raf);
raf = 0;
}
};
const io = new IntersectionObserver(([e]) => {
visible = e.isIntersecting;
sync();
});
io.observe(host);
const ro = new ResizeObserver(() => {
resize();
layoutText();
render();
});
ro.observe(host);
// re-lay the words when the text reflows: resize, fonts arriving, text splitting
let mo: MutationObserver | null = null;
if (textEl) {
ro.observe(textEl);
mo = new MutationObserver(() => {
layoutText();
render();
});
mo.observe(textEl, { childList: true, subtree: true, characterData: true });
document.fonts?.ready.then(() => {
layoutText();
render();
});
}
document.addEventListener("visibilitychange", sync);
if (reduced) {
// a still, softly rippled surface instead of motion
for (let k = 0; k < 6; k++) {
simulate(0, -999, -999, -999, -999, { x: sw * (0.15 + 0.14 * k), y: sh * (0.3 + 0.08 * (k % 3)), r: 5, s: 0.8 });
}
for (let k = 0; k < 40; k++) simulate(0, -999, -999, -999, -999, null);
render();
}
// a still frame picks up colour / intensity tweaks right away
redraw.current = render;
return () => {
redraw.current = null;
cancelAnimationFrame(raf);
io.disconnect();
ro.disconnect();
mo?.disconnect();
if (textEl) textEl.style.opacity = "";
document.removeEventListener("visibilitychange", sync);
window.removeEventListener("pointermove", onMove);
window.removeEventListener("pointerdown", onDown);
document.removeEventListener("pointerout", onOut);
gl.getExtension("WEBGL_lose_context")?.loseContext();
canvas.remove();
};
}, [text]);
return (
<div
ref={hostRef}
aria-hidden="true"
className={["pointer-events-none bg-black", className].filter(Boolean).join(" ")}
/>
);
}
›Plain CSS variant (no Tailwind)
components/inreact/liquid-obsidian.tsx
"use client";
import { useEffect, useRef } from "react";
import "./liquid-obsidian.css";
/**
* Liquid Obsidian: the background becomes a sheet of black, glossy liquid
* lit by hidden studio lights.
*
* - At rest it is almost pure black; stray droplets send soft rings across it.
* - The cursor drags through the surface and leaves a real wake (a GPU wave
* simulation). The waves bend the light, so ripples flash with the light
* colours across the black.
* - Click drops a stone: a ring wave crosses the whole section and reflects
* off the edges.
* - Optional: sink a headline under the surface so the ripples bend it.
*
* Usage: place it as the first child of a positioned section.
*
* <section className="relative isolate overflow-hidden">
* <LiquidObsidian className="absolute inset-0 -z-10" text="[data-sink]" />
* <h2 data-sink>Make waves.</h2>
* </section>
*
* Needs WebGL2 with float render targets; otherwise it falls back to a still,
* lit-liquid gradient and leaves the text untouched. Pauses off-screen and
* honours prefers-reduced-motion. Colours and sliders update live, without
* restarting the simulation.
*/
export interface LiquidObsidianProps {
className?: string;
/** First studio light (top-left). */
lightA?: string;
/** Second studio light (bottom-right). */
lightB?: string;
/** How long ripples live: 0.95 (short) to 0.995 (long). */
damping?: number;
/** Brightness of the reflections. */
intensity?: number;
/** Ambient droplets per second (0 to turn off). */
rain?: number;
/**
* CSS selector (searched inside the parent element) of text to sink under
* the surface. It is redrawn inside the liquid and bends with the ripples,
* while the real DOM text stays in place, invisible, for selection and
* screen readers. Per-word opacity (e.g. a scroll reveal) is mirrored.
*/
text?: string;
/** How far ripples bend the submerged text, in CSS px. */
refraction?: number;
}
const VERT = `#version 300 es
in vec2 p;
out vec2 vUv;
void main() {
vUv = p * 0.5 + 0.5;
gl_Position = vec4(p, 0.0, 1.0);
}`;
/* Wave equation on a height field. r = height now, g = height last step. */
const SIM = `#version 300 es
precision highp float;
uniform sampler2D uState;
uniform vec2 uTexel;
uniform vec2 uSize;
uniform vec2 uA;
uniform vec2 uB;
uniform float uForce;
uniform float uRadius;
uniform vec4 uDrop;
uniform float uDamp;
in vec2 vUv;
out vec4 o;
float capsule(vec2 p, vec2 a, vec2 b) {
vec2 pa = p - a, ba = b - a;
float h = clamp(dot(pa, ba) / max(dot(ba, ba), 1e-4), 0.0, 1.0);
return length(pa - ba * h);
}
void main() {
vec4 s = texture(uState, vUv);
float l = texture(uState, vUv - vec2(uTexel.x, 0.0)).r;
float r = texture(uState, vUv + vec2(uTexel.x, 0.0)).r;
float d = texture(uState, vUv - vec2(0.0, uTexel.y)).r;
float u = texture(uState, vUv + vec2(0.0, uTexel.y)).r;
float h = (l + r + d + u) * 0.5 - s.g;
h *= uDamp;
vec2 p = vUv * uSize;
float dc = capsule(p, uA, uB);
h -= uForce * exp(-dc * dc / (uRadius * uRadius));
float dd = length(p - uDrop.xy);
h -= uDrop.w * exp(-dd * dd / (uDrop.z * uDrop.z));
o = vec4(clamp(h, -8.0, 8.0), s.r, 0.0, 1.0);
}`;
/* Shade the surface: normals from the height field, reflected into two soft
coloured lights and a thin white key light. Flat liquid stays black.
Optional submerged text is refracted through the surface. */
const RENDER = `#version 300 es
precision highp float;
uniform sampler2D uState;
uniform sampler2D uText;
uniform vec2 uTexel;
uniform vec3 uLightA;
uniform vec3 uLightB;
uniform float uIntensity;
uniform float uAspect;
uniform vec4 uGuard;
uniform vec4 uTextBox;
uniform float uHasText;
uniform vec2 uRefract;
in vec2 vUv;
out vec4 o;
void main() {
float hl = texture(uState, vUv - vec2(uTexel.x, 0.0)).r;
float hr = texture(uState, vUv + vec2(uTexel.x, 0.0)).r;
float hd = texture(uState, vUv - vec2(0.0, uTexel.y)).r;
float hu = texture(uState, vUv + vec2(0.0, uTexel.y)).r;
vec3 n = normalize(vec3((hl - hr) * 3.2, (hd - hu) * 3.2, 1.0));
vec3 R = reflect(vec3(0.0, 0.0, -1.0), n);
// light directions drift slightly across the section for a studio feel
vec2 q = vUv - 0.5;
q.x *= uAspect;
vec3 La = normalize(vec3(-0.55 - q.x * 0.25, 0.55 - q.y * 0.25, 0.62));
vec3 Lb = normalize(vec3(0.6 - q.x * 0.25, -0.45 - q.y * 0.25, 0.66));
vec3 Lk = normalize(vec3(0.05, 0.75, 0.66));
float sa = pow(max(dot(R, La), 0.0), 26.0);
float sb = pow(max(dot(R, Lb), 0.0), 26.0);
float sk = pow(max(dot(R, Lk), 0.0), 160.0);
float slope = length(n.xy);
vec3 spec = (uLightA * sa * 1.6 + uLightB * sb * 1.9 + vec3(1.0, 0.98, 0.95) * sk * 1.1) * uIntensity;
vec3 col = vec3(0.006) + spec + vec3(0.05, 0.05, 0.06) * smoothstep(0.0, 0.6, slope) * uIntensity;
// calmer reflections around the headline so the words always win
vec2 gp = vec2(vUv.x, 1.0 - vUv.y);
vec2 gd = max(uGuard.xy - gp, gp - uGuard.zw);
float inGuard = 1.0 - smoothstep(0.0, 0.08, max(gd.x, gd.y));
col *= 1.0 - 0.5 * inGuard;
// melt into the page at the top and bottom
float fade = smoothstep(0.0, 0.12, vUv.y) * smoothstep(1.0, 0.88, vUv.y);
col *= fade;
// a whisper of filmic roll-off so hot glints stay rich, not clipped
col = col / (1.0 + col * 0.25);
if (uHasText > 0.5) {
// the text lies under the surface: ripples bend it, with a hair of dispersion
vec2 tb = uTextBox.zw - uTextBox.xy;
vec2 tuv = (vUv - uTextBox.xy) / tb;
// bend, but never so far that a word stops reading: cap the offset
vec2 bend = n.xy;
float bl = length(bend);
bend *= min(1.0, 0.45 / max(bl, 1e-4));
vec2 off = (bend * uRefract) / tb;
vec4 tr = texture(uText, tuv + off * 1.1);
vec4 tg = texture(uText, tuv + off);
vec4 tbl = texture(uText, tuv + off * 0.9);
vec3 trgb = vec3(tr.r, tg.g, tbl.b);
float ta = max(tg.a, max(tr.a, tbl.a));
// light gathered by the moving surface brightens the letters (caustics)
trgb *= 1.0 + smoothstep(0.02, 0.5, slope) * 0.45;
col = col * (1.0 - ta) + trgb;
// the surface sits above the words: its glints slide across them
vec3 glint = spec * 0.45 * ta * fade;
col += glint / (1.0 + glint);
}
o = vec4(col, 1.0);
}`;
const isReducedMotion = () =>
typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
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];
}
function program(gl: WebGL2RenderingContext, vsSrc: string, fsSrc: string) {
const make = (type: number, src: string) => {
const s = gl.createShader(type)!;
gl.shaderSource(s, src);
gl.compileShader(s);
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {
console.error(gl.getShaderInfoLog(s));
return null;
}
return s;
};
const vs = make(gl.VERTEX_SHADER, vsSrc);
const fs = make(gl.FRAGMENT_SHADER, fsSrc);
if (!vs || !fs) return null;
const p = gl.createProgram()!;
gl.attachShader(p, vs);
gl.attachShader(p, fs);
gl.bindAttribLocation(p, 0, "p");
gl.linkProgram(p);
if (!gl.getProgramParameter(p, gl.LINK_STATUS)) {
console.error(gl.getProgramInfoLog(p));
return null;
}
return p;
}
export function LiquidObsidian({
className,
lightA = "#ff4d00",
lightB = "#2b5cff",
damping = 0.98,
intensity = 1,
rain = 1.6,
text,
refraction = 10,
}: LiquidObsidianProps) {
const hostRef = useRef<HTMLDivElement>(null);
// live settings: read every frame, so tweaks never restart the simulation
const live = useRef({ lightA, lightB, damping, intensity, rain, refraction });
const redraw = useRef<(() => void) | null>(null);
useEffect(() => {
live.current = { lightA, lightB, damping, intensity, rain, refraction };
redraw.current?.();
}, [lightA, lightB, damping, intensity, rain, refraction]);
useEffect(() => {
const host = hostRef.current;
if (!host) return;
const canvas = document.createElement("canvas");
canvas.setAttribute("aria-hidden", "true");
canvas.style.cssText = "display:block;width:100%;height:100%";
host.appendChild(canvas);
const gl = canvas.getContext("webgl2", { antialias: false, alpha: false, depth: false, stencil: false });
const floatOk = !!gl && !!gl.getExtension("EXT_color_buffer_float");
if (!gl || !floatOk) {
// no float render targets: keep a still, lit-liquid look
canvas.remove();
host.style.background =
"radial-gradient(60% 50% at 18% 30%, rgba(255,77,0,0.10), transparent 70%), radial-gradient(55% 45% at 85% 75%, rgba(43,92,255,0.12), transparent 70%), #000";
return;
}
const simProg = program(gl, VERT, SIM);
const renProg = program(gl, VERT, RENDER);
if (!simProg || !renProg) return;
const vao = gl.createVertexArray();
gl.bindVertexArray(vao);
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);
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
const S = (n: string) => gl.getUniformLocation(simProg, n);
const Rn = (n: string) => gl.getUniformLocation(renProg, n);
const su = {
state: S("uState"),
texel: S("uTexel"),
size: S("uSize"),
a: S("uA"),
b: S("uB"),
force: S("uForce"),
radius: S("uRadius"),
drop: S("uDrop"),
damp: S("uDamp"),
};
const ru = {
state: Rn("uState"),
texel: Rn("uTexel"),
la: Rn("uLightA"),
lb: Rn("uLightB"),
intensity: Rn("uIntensity"),
aspect: Rn("uAspect"),
guard: Rn("uGuard"),
text: Rn("uText"),
textBox: Rn("uTextBox"),
hasText: Rn("uHasText"),
refract: Rn("uRefract"),
};
/* ---------- ping-pong height field ---------- */
type Target = { tex: WebGLTexture; fbo: WebGLFramebuffer };
let targets: Target[] = [];
let cur = 0;
let sw = 1;
let sh = 1;
let w = 1;
let h = 1;
let simScale = 0.25;
const makeTarget = (): Target => {
const tex = gl.createTexture()!;
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA16F, sw, sh, 0, gl.RGBA, gl.HALF_FLOAT, null);
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);
const fbo = gl.createFramebuffer()!;
gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
gl.clearColor(0, 0, 0, 1);
gl.clear(gl.COLOR_BUFFER_BIT);
return { tex, fbo };
};
const resize = () => {
w = Math.max(1, host.clientWidth);
h = Math.max(1, host.clientHeight);
const dpr = Math.min(window.devicePixelRatio || 1, 1.5);
canvas.width = Math.round(w * dpr);
canvas.height = Math.round(h * dpr);
// ~4 css px per simulation cell; coarser on small screens
simScale = w < 768 ? 0.2 : 0.25;
sw = Math.max(32, Math.round(w * simScale));
sh = Math.max(32, Math.round(h * simScale));
targets.forEach((t) => {
gl.deleteTexture(t.tex);
gl.deleteFramebuffer(t.fbo);
});
targets = [makeTarget(), makeTarget()];
cur = 0;
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
};
resize();
/* ---------- input ---------- */
const ptr = { cx: -1, cy: -1, has: false, sx: 0, sy: 0, psx: 0, psy: 0, primed: false };
let drop: { x: number; y: number; r: number; s: number } | null = null;
const onMove = (e: PointerEvent) => {
ptr.cx = e.clientX;
ptr.cy = e.clientY;
ptr.has = true;
};
const onDown = (e: PointerEvent) => {
const r = host.getBoundingClientRect();
const x = e.clientX - r.left;
const y = e.clientY - r.top;
if (x < 0 || y < 0 || x > r.width || y > r.height) return;
drop = { x: x * simScale, y: (h - y) * simScale, r: 10, s: 1.9 };
};
const onOut = (e: PointerEvent) => {
if (!e.relatedTarget) ptr.has = false;
};
window.addEventListener("pointermove", onMove, { passive: true });
window.addEventListener("pointerdown", onDown, { passive: true });
document.addEventListener("pointerout", onOut);
/* ---------- submerged text ---------- */
const textEl = text ? (host.parentElement?.querySelector(text) as HTMLElement | null) : null;
const tcan = document.createElement("canvas");
const tctx = tcan.getContext("2d")!;
const textTex = gl.createTexture()!;
gl.bindTexture(gl.TEXTURE_2D, textTex);
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);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(4));
type Run = { s: string; x: number; y: number; font: string; ls: string; color: string; chain: HTMLElement[] };
let runs: Run[] = [];
let ops: number[] = [];
let textReady = false;
const MARGIN = 40;
let box = { x: 0, y: 0, w: 1, h: 1 };
let guardBox: [number, number, number, number] = [2, 2, -1, -1];
const layoutText = () => {
if (!textEl) return;
const hr = host.getBoundingClientRect();
const er = textEl.getBoundingClientRect();
guardBox = [
(er.left - hr.left) / hr.width,
(er.top - hr.top) / hr.height,
(er.right - hr.left) / hr.width,
(er.bottom - hr.top) / hr.height,
];
box = { x: er.left - hr.left - MARGIN, y: er.top - hr.top - MARGIN, w: er.width + MARGIN * 2, h: er.height + MARGIN * 2 };
const tdpr = Math.min(window.devicePixelRatio || 1, 2);
tcan.width = Math.max(1, Math.round(box.w * tdpr));
tcan.height = Math.max(1, Math.round(box.h * tdpr));
tctx.setTransform(tdpr, 0, 0, tdpr, 0, 0);
runs = [];
const walker = document.createTreeWalker(textEl, NodeFilter.SHOW_TEXT);
const range = document.createRange();
const ascents = new Map<string, number>();
let node: Node | null;
while ((node = walker.nextNode())) {
const str = node.textContent ?? "";
const parent = node.parentElement;
if (!parent || !str.trim()) continue;
const cs = getComputedStyle(parent);
const font = `${cs.fontStyle} ${cs.fontWeight} ${cs.fontSize} ${cs.fontFamily}`;
if (!ascents.has(font)) {
tctx.font = font;
ascents.set(font, tctx.measureText("Hg").fontBoundingBoxAscent);
}
const chain: HTMLElement[] = [];
for (let e: HTMLElement | null = parent; e && e !== textEl; e = e.parentElement) chain.push(e);
const re = /\S+/g;
let m: RegExpExecArray | null;
while ((m = re.exec(str))) {
range.setStart(node, m.index);
range.setEnd(node, m.index + m[0].length);
const rect = range.getClientRects()[0];
if (!rect) continue;
runs.push({
s: m[0],
x: rect.left - hr.left - box.x,
y: rect.top - hr.top - box.y + (ascents.get(font) ?? rect.height * 0.8),
font,
ls: cs.letterSpacing,
color: cs.color,
chain,
});
}
}
ops = runs.map(() => -1);
};
// redraw the words only when their reveal opacity actually changes
const syncText = () => {
if (!textEl || !runs.length) return;
let dirty = false;
for (let i = 0; i < runs.length; i++) {
let op = 1;
for (const e of runs[i].chain) {
const v = e.style.opacity;
if (v) op *= parseFloat(v);
}
op = Math.round(op * 48) / 48;
if (op !== ops[i]) {
ops[i] = op;
dirty = true;
}
}
if (!dirty) return;
tctx.clearRect(0, 0, box.w, box.h);
for (let i = 0; i < runs.length; i++) {
const run = runs[i];
if (ops[i] <= 0) continue;
tctx.globalAlpha = ops[i];
tctx.font = run.font;
(tctx as CanvasRenderingContext2D & { letterSpacing: string }).letterSpacing = run.ls;
tctx.fillStyle = run.color;
tctx.fillText(run.s, run.x, run.y);
}
tctx.globalAlpha = 1;
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_2D, textTex);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, tcan);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
if (!textReady) {
// the liquid now draws the words: hide the DOM copy (still selectable and read aloud)
textReady = true;
textEl.style.opacity = "0";
}
};
/* ---------- passes ---------- */
const simulate = (force: number, ax: number, ay: number, bx: number, by: number, d: typeof drop) => {
const src = targets[cur];
const dst = targets[1 - cur];
gl.useProgram(simProg);
gl.bindFramebuffer(gl.FRAMEBUFFER, dst.fbo);
gl.viewport(0, 0, sw, sh);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, src.tex);
gl.uniform1i(su.state, 0);
gl.uniform2f(su.texel, 1 / sw, 1 / sh);
gl.uniform2f(su.size, sw, sh);
gl.uniform2f(su.a, ax, ay);
gl.uniform2f(su.b, bx, by);
gl.uniform1f(su.force, force);
gl.uniform1f(su.radius, 3.2);
gl.uniform4f(su.drop, d ? d.x : -999, d ? d.y : -999, d ? d.r : 1, d ? d.s : 0);
gl.uniform1f(su.damp, Math.sqrt(live.current.damping));
gl.drawArrays(gl.TRIANGLES, 0, 3);
cur = 1 - cur;
};
const render = () => {
const L = live.current;
gl.useProgram(renProg);
gl.uniform3fv(ru.la, hexToRgb(L.lightA));
gl.uniform3fv(ru.lb, hexToRgb(L.lightB));
gl.uniform1f(ru.intensity, L.intensity);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.viewport(0, 0, canvas.width, canvas.height);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, targets[cur].tex);
gl.uniform1i(ru.state, 0);
gl.uniform2f(ru.texel, 1 / sw, 1 / sh);
gl.uniform1f(ru.aspect, w / h);
gl.uniform4f(ru.guard, guardBox[0], guardBox[1], guardBox[2], guardBox[3]);
syncText();
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_2D, textTex);
gl.uniform1i(ru.text, 1);
gl.uniform1f(ru.hasText, textReady ? 1 : 0);
// text box in surface uv space (origin bottom-left)
gl.uniform4f(ru.textBox, box.x / w, 1 - (box.y + box.h) / h, (box.x + box.w) / w, 1 - box.y / h);
gl.uniform2f(ru.refract, L.refraction / w, L.refraction / h);
gl.drawArrays(gl.TRIANGLES, 0, 3);
};
/* ---------- loop ---------- */
const reduced = isReducedMotion();
let rainClock = 0;
let acc = 0;
const STEP = 1 / 60;
const tick = (dt: number) => {
const r = host.getBoundingClientRect();
const inside = ptr.has && ptr.cx >= r.left && ptr.cx <= r.right && ptr.cy >= r.top && ptr.cy <= r.bottom;
// pointer in simulation space (origin bottom-left)
const sx = (ptr.cx - r.left) * simScale;
const sy = (h - (ptr.cy - r.top)) * simScale;
if (inside && !ptr.primed) {
ptr.psx = sx;
ptr.psy = sy;
ptr.primed = true;
}
if (!inside) ptr.primed = false;
// fixed-step physics so the waves behave the same on 60/120/144 Hz screens
acc = Math.min(acc + dt, STEP * 4);
const steps = Math.floor(acc / STEP);
acc -= steps * STEP;
for (let k = 0; k < steps; k++) {
let force = 0;
let ax = -999;
let ay = -999;
let bx = -999;
let by = -999;
if (inside) {
// walk the segment from last to current position across the steps
const t0 = k / steps;
const t1 = (k + 1) / steps;
ax = ptr.psx + (sx - ptr.psx) * t0;
ay = ptr.psy + (sy - ptr.psy) * t0;
bx = ptr.psx + (sx - ptr.psx) * t1;
by = ptr.psy + (sy - ptr.psy) * t1;
const moved = Math.hypot(bx - ax, by - ay);
force = Math.min(0.55, moved * 0.09);
}
let d: typeof drop = null;
if (k === 0 && drop) {
d = drop;
drop = null;
} else if (live.current.rain > 0) {
rainClock += STEP;
if (rainClock > 1 / live.current.rain) {
rainClock = 0;
d = { x: Math.random() * sw, y: sh * (0.15 + Math.random() * 0.7), r: 2.6 + Math.random() * 2.2, s: 0.55 + Math.random() * 0.45 };
}
}
// two wave sub-steps per physics step: ripples travel twice as fast
simulate(force, ax, ay, bx, by, d);
simulate(0, -999, -999, -999, -999, null);
}
if (inside) {
ptr.psx = sx;
ptr.psy = sy;
}
render();
};
let raf = 0;
let visible = false;
let last = 0;
const frame = (now: number) => {
raf = requestAnimationFrame(frame);
const dt = last ? Math.min(0.1, (now - last) / 1000) : STEP;
last = now;
tick(dt);
};
const sync = () => {
const go = visible && !document.hidden && !reduced;
if (go && !raf) {
last = 0;
raf = requestAnimationFrame(frame);
} else if (!go && raf) {
cancelAnimationFrame(raf);
raf = 0;
}
};
const io = new IntersectionObserver(([e]) => {
visible = e.isIntersecting;
sync();
});
io.observe(host);
const ro = new ResizeObserver(() => {
resize();
layoutText();
render();
});
ro.observe(host);
// re-lay the words when the text reflows: resize, fonts arriving, text splitting
let mo: MutationObserver | null = null;
if (textEl) {
ro.observe(textEl);
mo = new MutationObserver(() => {
layoutText();
render();
});
mo.observe(textEl, { childList: true, subtree: true, characterData: true });
document.fonts?.ready.then(() => {
layoutText();
render();
});
}
document.addEventListener("visibilitychange", sync);
if (reduced) {
// a still, softly rippled surface instead of motion
for (let k = 0; k < 6; k++) {
simulate(0, -999, -999, -999, -999, { x: sw * (0.15 + 0.14 * k), y: sh * (0.3 + 0.08 * (k % 3)), r: 5, s: 0.8 });
}
for (let k = 0; k < 40; k++) simulate(0, -999, -999, -999, -999, null);
render();
}
// a still frame picks up colour / intensity tweaks right away
redraw.current = render;
return () => {
redraw.current = null;
cancelAnimationFrame(raf);
io.disconnect();
ro.disconnect();
mo?.disconnect();
if (textEl) textEl.style.opacity = "";
document.removeEventListener("visibilitychange", sync);
window.removeEventListener("pointermove", onMove);
window.removeEventListener("pointerdown", onDown);
document.removeEventListener("pointerout", onOut);
gl.getExtension("WEBGL_lose_context")?.loseContext();
canvas.remove();
};
}, [text]);
return (
<div
ref={hostRef}
aria-hidden="true"
className={["liquid-obsidian", className].filter(Boolean).join(" ")}
/>
);
}
components/inreact/liquid-obsidian.css
.liquid-obsidian {
pointer-events: none;
background: #000;
}
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
8 propslightAstringFirst studio light, top-left. Any hex colour.default "#ff4d00"default "#ff4d00"lightBstringSecond studio light, bottom-right.default "#2b5cff"default "#2b5cff"intensitynumberBrightness of the reflections.default 1default 1dampingnumberHow long ripples live: 0.95 (short) to 0.995 (long).default 0.98default 0.98rainnumberAmbient droplets per second. 0 turns them off.default 1.6default 1.6textstringCSS selector, searched inside the parent element, of text to sink under the surface. The real text stays in the DOM, invisible, for selection and screen readers.refractionnumberHow far ripples bend the sunk text, in CSS px.default 10default 10classNamestringPosition and size it, e.g. absolute inset-0 -z-10.