Warp Gallery
A strip of framed photos seen through a lens, turned by scroll. The centre frame sits in a clear window; beyond it the view bends like light around a black hole: toward the sides the strip is magnified harder and harder, the band bows, the corners swirl and colour splits at the rims. The section pins while the page scrolls, the strip glides through the lens with smooth inertia and settles onto a frame; the faster you scroll, the stronger the lensing, and each photo has depth-map parallax.
Tweak
LIVELIVELook
Tone
Scroll
Settle onto a frame
Usage
Follows your tweaks.
import { WarpGallery } from "@/components/inreact/warp-gallery";
const items = [
{ src: "/products/01.jpg", depth: "/products/01-depth.png", title: "Canopy", label: "No. 01" },
{ src: "/products/02.jpg", depth: "/products/02-depth.png", title: "Velvet", label: "No. 02" },
// ...portrait photos; depth maps optional (white = near)
];
// pins while the page scrolls through it, turning the ring
export function Collection() {
return <WarpGallery items={items} />;
}Install with the CLI
npx shadcn@latest add https://inreact.vercel.app/r/warp-gallery.jsonOr copy the source
Install the dependencies, then save this as components/inreact/warp-gallery.tsx.
npm install gsap three"use client";
import { gsap } from "gsap";
import { ScrollToPlugin } from "gsap/ScrollToPlugin";
import * as THREE from "three";
import { useEffect, useRef, useState, type CSSProperties } from "react";
gsap.registerPlugin(ScrollToPlugin);
/**
* Warp Gallery: a strip of framed photos seen through a lens, turned by scroll.
*
* The centre frame sits in a flat, clear window. Beyond it the view bends like
* light around a black hole: toward the sides the strip is magnified harder and
* harder, the band grows taller so its edges bow and the corners tilt, and colour splits at the
* rims. Scroll and the strip glides through the lens (the section pins while
* the page scrolls), following with inertia and settling onto a frame when you
* stop; the faster you scroll, the stronger the lensing. Each photo can carry a
* depth map, so near things slide further than far ones as it moves.
*
* // pinned in the page (default): give it room to scroll through
* <WarpGallery items={items} />
* // or inside its own scroll box
* <WarpGallery items={items} scroll="self" className="h-[600px]" />
*/
export interface WarpGalleryItem {
src: string;
title: string;
/** Small label at the frame's top corner. */
label?: string;
/** Depth map (white = near) for parallax inside the frame. */
depth?: string;
alt?: string;
}
export interface WarpGalleryProps {
items: WarpGalleryItem[];
/** "page": the section pins while the page scrolls; "self": it scrolls inside its own box. */
scroll?: "page" | "self";
/** Scroll distance per frame, in viewport (or box) heights. */
pace?: number;
/** Settle onto the nearest frame when scrolling stops. */
snap?: boolean;
/** Light band for light pages, dark band for dark ones. */
tone?: "light" | "dark";
/** Lens strength at the sides (0 = flat). */
lens?: number;
onChange?: (index: number) => void;
className?: string;
}
const reduced = () => typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
// ---- pass 1: the flat strip -------------------------------------------------
const FRAME_VERT = /* glsl */ `
varying vec2 vUv;
void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }
`;
const FRAME_FRAG = /* glsl */ `
precision highp float;
uniform sampler2D uFrame;
uniform sampler2D uPhoto;
uniform sampler2D uDepth;
uniform vec2 uSize; // frame, px
uniform vec4 uRect; // photo rect, px: x0, y0, x1, y1 (y up)
uniform float uRadius;
uniform float uAspect;
uniform float uReady;
uniform float uPar; // depth parallax
uniform float uHasDepth;
varying vec2 vUv;
float sdRound(vec2 p, vec2 b, float r) {
vec2 q = abs(p) - b + r;
return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - r;
}
void main() {
vec4 fr = texture2D(uFrame, vUv);
vec2 px = vUv * uSize;
vec2 c = (uRect.xy + uRect.zw) * 0.5;
vec2 hs = (uRect.zw - uRect.xy) * 0.5;
float d = sdRound(px - c, hs, uRadius);
float aa = max(fwidth(d), 1e-4) * 0.8;
float m = 1.0 - smoothstep(-aa, aa, d);
vec2 local = (px - c) / (hs * 2.0);
float ra = hs.x / hs.y;
if (uAspect > ra) local.x *= ra / uAspect; else local.y *= uAspect / ra;
vec2 uv = local / 1.04 + 0.5;
float dep = uHasDepth > 0.5 ? texture2D(uDepth, uv).r : 0.5;
uv.x += (dep - 0.5) * uPar;
vec3 ph = texture2D(uPhoto, clamp(uv, 0.0, 1.0)).rgb;
vec3 col = mix(fr.rgb, ph, m * uReady);
gl_FragColor = vec4(col, fr.a);
}
`;
// ---- pass 2: the lens --------------------------------------------------------
// a clear window in the middle; beyond it magnification ramps up toward the
// sides (an arctan falloff) and the band grows taller, so its edges bow and the
// corners tilt; colour splits a little at the rims
const LENS_VERT = /* glsl */ `
varying vec2 vUv;
void main() { vUv = uv; gl_Position = vec4(position.xy, 0.0, 1.0); }
`;
const LENS_FRAG = /* glsl */ `
precision highp float;
uniform sampler2D uScene;
uniform vec2 uRes; // px
uniform float uWin; // half-width of the clear window, px
uniform float uA; // horizontal magnification ramp
uniform float uB; // vertical magnification ramp
uniform float uSwirl; // corner swirl
uniform float uSplit; // colour split
varying vec2 vUv;
vec2 lens(vec2 p, float k) {
// p: px from the centre (y up)
float ax = abs(p.x);
float span = max(uRes.x * 0.5 - uWin, 1.0);
float t = max(ax - uWin, 0.0) / span; // 0 at the window edge, 1 at the screen edge
float A = uA * k;
float sa = sqrt(max(A, 1e-4));
float ts = atan(sa * t) / sa; // magnified: the source moves slower than the screen
float m = 1.0 + uB * k * t * t;
vec2 s = vec2(sign(p.x) * (min(ax, uWin) + ts * span), p.y / m);
// swirl the corners about the window edge, harder toward the outside and away from the middle
float ang = uSwirl * k * t * t * (p.y / (uRes.y * 0.5)) * sign(p.x);
vec2 o = vec2(sign(p.x) * uWin, 0.0);
vec2 q = s - o;
float c = cos(ang), sn = sin(ang);
s = o + vec2(c * q.x - sn * q.y, sn * q.x + c * q.y);
return s;
}
vec4 sampleAt(vec2 s) {
vec2 uv = s / uRes + 0.5;
if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) return vec4(0.0);
return texture2D(uScene, uv);
}
void main() {
vec2 p = (vUv - 0.5) * uRes;
float span = max(uRes.x * 0.5 - uWin, 1.0);
float t = max(abs(p.x) - uWin, 0.0) / span;
float sp = uSplit * t * t;
vec4 g = sampleAt(lens(p, 1.0));
vec4 r = sampleAt(lens(p, 1.0 + sp));
vec4 b = sampleAt(lens(p, 1.0 - sp));
gl_FragColor = vec4(r.r, g.g, b.b, g.a);
}
`;
export function WarpGallery({ items, scroll = "page", pace = 0.6, snap = true, tone = "light", lens = 1, onChange, className }: WarpGalleryProps) {
const outerRef = useRef<HTMLDivElement>(null);
const hostRef = useRef<HTMLDivElement>(null);
const [index, setIndex] = useState(0);
const cb = useRef(onChange);
cb.current = onChange;
const n = items.length;
const key = items.map((i) => `${i.src}|${i.title}|${i.label ?? ""}|${i.depth ?? ""}`).join(",");
useEffect(() => {
const outer = outerRef.current, host = hostRef.current;
if (!outer || !host || n === 0) return;
const still = reduced();
const dark = tone === "dark";
const fontFamily = getComputedStyle(outer).fontFamily || "system-ui, sans-serif";
const canvas = document.createElement("canvas");
canvas.style.cssText = "position:absolute;inset:0;width:100%;height:100%;display:block;";
host.appendChild(canvas);
let renderer: THREE.WebGLRenderer;
try {
renderer = new THREE.WebGLRenderer({ canvas, antialias: false, alpha: true, premultipliedAlpha: true });
} catch {
canvas.remove();
return;
}
const pr = Math.min(window.devicePixelRatio || 1, 2);
renderer.setPixelRatio(pr);
renderer.setClearColor(0x000000, 0);
// pass 1 renders into this, supersampled so the magnified sides stay sharp
const ss = 1.5;
const rt = new THREE.WebGLRenderTarget(4, 4, { samples: 4, generateMipmaps: false, minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter });
const scene = new THREE.Scene();
const camera = new THREE.OrthographicCamera(-1, 1, 1, -1, -10, 10);
const lensMat = new THREE.ShaderMaterial({
vertexShader: LENS_VERT,
fragmentShader: LENS_FRAG,
transparent: true,
depthTest: false,
uniforms: {
uScene: { value: rt.texture },
uRes: { value: new THREE.Vector2(1, 1) },
uWin: { value: 100 },
uA: { value: 6 },
uB: { value: 0.6 },
uSwirl: { value: 0.5 },
uSplit: { value: 0.03 },
},
});
const lensScene = new THREE.Scene();
const lensQuad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), lensMat);
lensQuad.frustumCulled = false;
lensScene.add(lensQuad);
const lensCam = new THREE.Camera();
const L = { W: 1, H: 1, band: 1, fw: 1 };
const loader = new THREE.TextureLoader();
const aniso = renderer.capabilities.getMaxAnisotropy();
const loadTex = (src: string, onLoad: (t: THREE.Texture) => void) =>
loader.load(src, (t) => {
t.colorSpace = THREE.NoColorSpace;
t.generateMipmaps = true;
t.minFilter = THREE.LinearMipmapLinearFilter;
t.anisotropy = aniso;
onLoad(t);
});
const photos = items.map((it) => {
const e = { tex: null as THREE.Texture | null, depth: null as THREE.Texture | null, aspect: 0.75, ready: 0 };
loadTex(it.src, (t) => {
const img = t.image as { width: number; height: number };
e.aspect = img.width / img.height;
e.tex = t;
gsap.to(e, { ready: 1, duration: still ? 0 : 0.7, ease: "power2.out" });
});
if (it.depth) loadTex(it.depth, (t) => (e.depth = t));
return e;
});
const blank = new THREE.DataTexture(new Uint8Array(dark ? [28, 28, 30, 255] : [232, 232, 236, 255]), 1, 1);
blank.needsUpdate = true;
type Frame = { mesh: THREE.Mesh; mat: THREE.ShaderMaterial; canvas: HTMLCanvasElement; tex: THREE.CanvasTexture; item: number };
const frames: Frame[] = [];
const paint = (f: Frame) => {
const it = items[f.item];
const fw = L.fw, bh = L.band;
// drawn at the size the lens can magnify it to, so text stays crisp at the sides
const sc = pr * ss * 1.4;
const c = f.canvas;
c.width = Math.round(fw * sc);
c.height = Math.round(bh * sc);
const g = c.getContext("2d")!;
g.setTransform(sc, 0, 0, sc, 0, 0);
g.fillStyle = dark ? "#141416" : "#ffffff";
g.fillRect(0, 0, fw, bh);
// hairline divider at the frame's left edge
g.fillStyle = dark ? "rgba(255,255,255,.14)" : "rgba(10,10,20,.16)";
g.fillRect(0, bh * 0.035, 1, bh * 0.93);
const ink = dark ? "rgba(255,255,255,.9)" : "rgba(12,12,16,.88)";
if (it.label) {
g.fillStyle = ink;
g.font = `500 ${Math.max(6, bh * 0.0135)}px ${fontFamily}`;
g.textBaseline = "top";
g.textAlign = "left";
g.fillText(it.label.toUpperCase(), 1 + bh * 0.012, bh * 0.033);
}
g.fillStyle = ink;
g.font = `500 ${Math.max(8, bh * 0.024)}px ${fontFamily}`;
g.textBaseline = "middle";
g.textAlign = "center";
g.fillText(it.title.toUpperCase(), fw / 2, bh * 0.955);
f.tex.needsUpdate = true;
const u = f.mat.uniforms;
u.uSize.value.set(fw, bh);
// photo inset: room for the label above and the name below
u.uRect.value.set(fw * 0.1, bh * 0.08, fw * 0.9, bh * 0.92 - bh * 0.02);
u.uRect.value.set(fw * 0.1, bh * 0.1, fw * 0.9, bh * 0.9);
u.uRadius.value = fw * 0.055;
f.mesh.geometry.dispose();
f.mesh.geometry = new THREE.PlaneGeometry(fw, bh);
};
const build = () => {
for (const f of frames) {
scene.remove(f.mesh);
f.mesh.geometry.dispose();
f.mat.dispose();
f.tex.dispose();
}
frames.length = 0;
const copies = Math.max(1, Math.ceil((L.W + L.fw * 4) / (n * L.fw)));
for (let j = 0; j < n * copies; j++) {
const c = document.createElement("canvas");
const tex = new THREE.CanvasTexture(c);
tex.colorSpace = THREE.NoColorSpace;
tex.generateMipmaps = true;
tex.minFilter = THREE.LinearMipmapLinearFilter;
tex.anisotropy = aniso;
const mat = new THREE.ShaderMaterial({
vertexShader: FRAME_VERT,
fragmentShader: FRAME_FRAG,
transparent: true,
uniforms: {
uFrame: { value: tex },
uPhoto: { value: blank },
uDepth: { value: blank },
uSize: { value: new THREE.Vector2(1, 1) },
uRect: { value: new THREE.Vector4() },
uRadius: { value: 8 },
uAspect: { value: 0.75 },
uReady: { value: 0 },
uPar: { value: 0 },
uHasDepth: { value: 0 },
},
});
const mesh = new THREE.Mesh(new THREE.PlaneGeometry(1, 1), mat);
const f = { mesh, mat, canvas: c, tex, item: j % n };
paint(f);
scene.add(mesh);
frames.push(f);
}
};
const resize = () => {
const r = host.getBoundingClientRect();
L.W = Math.max(1, r.width);
L.H = Math.max(1, r.height);
L.band = L.H * 0.88;
L.fw = Math.min(L.band * 0.56, L.W * 0.56);
renderer.setSize(L.W, L.H, false);
rt.setSize(Math.round(L.W * pr * ss), Math.round(L.H * pr * ss));
camera.left = -L.W / 2;
camera.right = L.W / 2;
camera.top = L.H / 2;
camera.bottom = -L.H / 2;
camera.updateProjectionMatrix();
lensMat.uniforms.uRes.value.set(L.W, L.H);
// the clear window holds the centre frame
lensMat.uniforms.uWin.value = L.fw * 0.5;
build();
};
resize();
document.fonts?.ready.then(() => frames.forEach(paint));
const ro = new ResizeObserver(resize);
ro.observe(host);
// scroll -> strip
const self = scroll === "self";
const progress = () => {
if (self) {
const max = outer.scrollHeight - outer.clientHeight;
return max > 0 ? outer.scrollTop / max : 0;
}
const r = outer.getBoundingClientRect();
const max = r.height - window.innerHeight;
return max > 0 ? Math.min(1, Math.max(0, -r.top / max)) : 0;
};
const st = { s: 0, v: 0, warp: 0 };
let lastScroll = performance.now();
let snapping = false;
const onScroll = () => {
if (!snapping) lastScroll = performance.now();
};
const scroller: HTMLElement | Window = self ? outer : window;
scroller.addEventListener("scroll", onScroll, { passive: true });
const trySnap = () => {
if (!snap || still || snapping || n < 2) return;
const span = n - 1;
const p = progress();
const target = Math.round(p * span) / span;
if (Math.abs(target - p) * span < 0.015) return;
snapping = true;
let y: number;
if (self) y = target * (outer.scrollHeight - outer.clientHeight);
else {
const r = outer.getBoundingClientRect();
y = window.scrollY + r.top + target * (r.height - window.innerHeight);
}
gsap.to(self ? outer : window, {
scrollTo: { y, autoKill: true },
duration: 0.9,
ease: "power3.inOut",
onComplete: () => void (snapping = false),
onInterrupt: () => void (snapping = false),
});
};
let visible = true;
const io = new IntersectionObserver(([e]) => (visible = e.isIntersecting));
io.observe(outer);
let current = -1;
const tick = (_t: number, dms: number) => {
const dt = Math.min(0.05, dms / 1000);
const target = progress() * (n - 1);
const k = still ? 1 : 1 - Math.exp(-dt * 6.5);
const prev = st.s;
st.s += (target - st.s) * k;
const v = (st.s - prev) / Math.max(dt, 1e-3);
st.v += (v - st.v) * Math.min(1, dt * 8);
if (!snapping && performance.now() - lastScroll > 200 && Math.abs(st.v) < 0.25) trySnap();
if (!visible) return;
// moving fast bends the light harder
const wGoal = still ? 0 : Math.min(Math.abs(st.v) * 0.12, 0.3);
st.warp += (wGoal - st.warp) * Math.min(1, dt * 5);
const total = frames.length * L.fw;
for (let j = 0; j < frames.length; j++) {
const f = frames[j];
let x = (j - st.s) * L.fw;
x = ((x % total) + total) % total;
if (x > total / 2) x -= total;
f.mesh.position.set(x, 0, 0);
const u = f.mat.uniforms;
// depth parallax: near things slide further as the frame travels
u.uPar.value = still ? 0 : -(x / L.W) * 0.09 - Math.sign(st.v) * st.warp * 0.05;
const p = photos[f.item];
if (p.tex && u.uPhoto.value !== p.tex) {
u.uPhoto.value = p.tex;
u.uAspect.value = p.aspect;
}
if (p.depth && u.uDepth.value !== p.depth) {
u.uDepth.value = p.depth;
u.uHasDepth.value = 1;
}
u.uReady.value = p.ready;
}
const lu = lensMat.uniforms;
const s = lens * (1 + st.warp);
// about 3x at the screen edge, the band growing ~1.5x taller there (which is what tilts the corners)
lu.uA.value = 2.6 * s;
lu.uB.value = 0.42 * s;
lu.uSwirl.value = 0;
lu.uSplit.value = (0.014 + st.warp * 0.02) * Math.min(1, lens);
renderer.setRenderTarget(rt);
renderer.clear();
renderer.render(scene, camera);
renderer.setRenderTarget(null);
renderer.clear();
renderer.render(lensScene, lensCam);
const idx = Math.min(n - 1, Math.max(0, Math.round(st.s)));
if (idx !== current) {
current = idx;
setIndex(idx);
cb.current?.(idx);
}
};
gsap.ticker.add(tick);
return () => {
gsap.ticker.remove(tick);
gsap.killTweensOf(self ? outer : window);
scroller.removeEventListener("scroll", onScroll);
io.disconnect();
ro.disconnect();
for (const f of frames) {
f.mesh.geometry.dispose();
f.mat.dispose();
f.tex.dispose();
}
photos.forEach((p) => {
p.tex?.dispose();
p.depth?.dispose();
});
blank.dispose();
rt.dispose();
lensMat.dispose();
lensQuad.geometry.dispose();
renderer.dispose();
canvas.remove();
};
// items are read by index; rebuild when their content changes
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [key, scroll, snap, tone, lens]);
const item = items[index];
const factor = Math.max(1, n - 1) * pace + 1;
const self = scroll === "self";
return (
<div
ref={outerRef}
role="region"
aria-roledescription="carousel"
aria-label="Gallery"
tabIndex={self ? 0 : undefined}
className={["relative w-full outline-none", self ? "h-full overflow-y-auto overscroll-contain [scrollbar-width:none] [&::-webkit-scrollbar]:hidden" : "", className].filter(Boolean).join(" ")}
style={self ? undefined : { height: `${factor * 100}vh` }}
>
<div className={self ? "relative" : "h-full"} style={self ? { height: `${factor * 100}%` } : undefined}>
<div className={self ? "sticky top-0" : "sticky top-0 h-screen"} style={self ? ({ height: `${100 / factor}%` } as CSSProperties) : undefined}>
<div ref={hostRef} className="absolute inset-0" />
</div>
</div>
<div aria-live="polite" className="sr-only">
{item ? `${index + 1} of ${n}: ${item.title}` : ""}
</div>
</div>
);
}
export default WarpGallery;
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 propsitems{ src; title; label?; depth?; alt? }[]The frames: a photo (portrait works best), its name, a corner label and an optional depth map (white = near).scroll"page" | "self"Pin while the page scrolls, or scroll inside its own box.default "page"default "page"pacenumberScroll distance per frame, in viewport heights.default 0.6default 0.6snapbooleanSettle onto the nearest frame when scrolling stops.default truedefault truetone"light" | "dark"Light band for light pages, dark band for dark ones.default "light"default "light"lensnumberLens strength at the sides (0 = flat).default 1default 1onChange(index) => voidCalled when a new frame reaches the centre.classNamestringExtra classes.