3D Tilt Gallery New
A grid of cards that tilt toward the pointer with a moving glare and floating captions; click one to zoom it open from where it sits.
Installation
01
Install with the shadcn CLI. The NiceUI theme comes along the first time.
$ npx shadcn@latest add https://niceui.dev/r/gallery-tilt-gallery.json02
Or copy the source below (2 files). Dependencies: lucide-react.
Source
components/niceui/gallery/TiltGallery.tsx
import { useEffect, useMemo, useRef, useState, type CSSProperties, type PointerEvent } from 'react';
import { MapPin, X } from 'lucide-react';
import { cn } from '@/lib/cn';
import { ARTWORKS, artwork, type Artwork } from './art';
export type TiltGalleryProps = {
items?: Artwork[];
src?: (item: Artwork) => string;
/** Maximum tilt in degrees. */
maxTilt?: number;
className?: string;
};
type Tilt = { id: number; rx: number; ry: number; gx: number; gy: number } | null;
type Open = { item: Artwork; from: DOMRect; box: DOMRect; expanded: boolean } | null;
/** A grid of cards that tilt toward the pointer with glare and floating captions; click to zoom one open. */
export function TiltGallery({ items = ARTWORKS.slice(0, 6), src = (a) => artwork(a.id, 800, 600), maxTilt = 12, className }: TiltGalleryProps) {
const [tilt, setTilt] = useState<Tilt>(null);
const [open, setOpen] = useState<Open>(null);
const box = useRef<HTMLDivElement>(null);
const urls = useMemo(() => new Map(items.map((a) => [a.id, src(a)])), [items, src]);
const reduce = typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
const onMove = (e: PointerEvent<HTMLButtonElement>, id: number) => {
if (reduce || e.pointerType === 'touch') return;
const r = e.currentTarget.getBoundingClientRect();
const px = (e.clientX - r.left) / r.width;
const py = (e.clientY - r.top) / r.height;
setTilt({ id, ry: (px - 0.5) * 2 * maxTilt, rx: -(py - 0.5) * 2 * maxTilt, gx: px * 100, gy: py * 100 });
};
const expand = (item: Artwork, el: HTMLElement) => {
const b = box.current;
if (!b) return;
setTilt(null);
setOpen({ item, from: el.getBoundingClientRect(), box: b.getBoundingClientRect(), expanded: false });
requestAnimationFrame(() => requestAnimationFrame(() => setOpen((o) => (o ? { ...o, expanded: true } : o))));
};
const close = () => {
setOpen((o) => (o ? { ...o, expanded: false } : o));
window.setTimeout(() => setOpen(null), reduce ? 0 : 420);
};
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && close();
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
});
// Overlay geometry, relative to the gallery box.
let frameStyle: CSSProperties = {};
if (open) {
const { from, box: bx, expanded } = open;
const pad = 12;
const maxW = bx.width - pad * 2;
const maxH = bx.height - pad * 2 - 72;
const ratio = from.width / from.height;
const w = Math.min(maxW, maxH * ratio);
const h = w / ratio;
frameStyle = expanded
? { left: (bx.width - w) / 2, top: pad, width: w, height: h }
: { left: from.left - bx.left, top: from.top - bx.top, width: from.width, height: from.height };
}
return (
<div ref={box} className={cn('relative w-full', className)}>
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 sm:gap-4">
{items.map((it) => {
const t = tilt?.id === it.id ? tilt : null;
return (
<button
key={it.id}
type="button"
aria-label={`Open ${it.title}`}
onPointerMove={(e) => onMove(e, it.id)}
onPointerLeave={() => setTilt((cur) => (cur?.id === it.id ? null : cur))}
onClick={(e) => expand(it, e.currentTarget)}
className={cn('focus-ring group relative aspect-[4/3] rounded-2xl', open?.item.id === it.id && 'opacity-0')}
style={{ transformStyle: 'preserve-3d', transform: `perspective(900px) rotateX(${t?.rx ?? 0}deg) rotateY(${t?.ry ?? 0}deg) scale(${t ? 1.03 : 1})`, transition: t ? 'transform 80ms linear' : 'transform 500ms cubic-bezier(.16,1,.3,1)' }}
>
<span className="absolute inset-0 overflow-hidden rounded-2xl shadow-card ring-1 ring-white/10">
<img src={urls.get(it.id)} alt="" draggable={false} className="h-full w-full object-cover" />
<span className="absolute inset-0 bg-gradient-to-t from-black/70 via-transparent to-transparent" />
<span
className="absolute inset-0 opacity-0 mix-blend-overlay transition-opacity duration-300 group-hover:opacity-100"
style={{ background: `radial-gradient(circle at ${t?.gx ?? 50}% ${t?.gy ?? 50}%, rgba(255,255,255,0.55), transparent 55%)` }}
/>
</span>
<span className="absolute inset-x-3 bottom-3 text-left" style={{ transform: 'translateZ(28px)' }}>
<span className="block truncate text-[13px] font-medium text-white drop-shadow sm:text-sm">{it.title}</span>
<span className="mt-0.5 hidden items-center gap-1 text-[11px] text-white/70 sm:flex">
<MapPin className="h-3 w-3" /> {it.place}
</span>
</span>
</button>
);
})}
</div>
{open && (
<div className="absolute inset-0 z-20" role="dialog" aria-modal="true" aria-label={open.item.title}>
<button aria-label="Close" onClick={close} className={cn('absolute inset-0 rounded-2xl bg-ink-950/80 backdrop-blur-sm transition-opacity duration-500', open.expanded ? 'opacity-100' : 'opacity-0')} />
<div className="absolute overflow-hidden rounded-2xl shadow-pop ring-1 ring-white/15 transition-all duration-500 ease-smooth" style={frameStyle}>
<img src={urls.get(open.item.id)} alt={open.item.title} className="h-full w-full object-cover" />
</div>
<div className={cn('absolute inset-x-0 bottom-3 flex items-end justify-between gap-3 px-4 transition-all duration-500', open.expanded ? 'translate-y-0 opacity-100' : 'translate-y-3 opacity-0')}>
<div className="min-w-0">
<p className="truncate font-serif text-2xl italic text-ink-50">{open.item.title}</p>
<p className="truncate text-xs text-ink-400">
{open.item.artist} · {open.item.place}, {open.item.year}
</p>
</div>
<button onClick={close} aria-label="Close" className="focus-ring grid h-9 w-9 shrink-0 place-items-center rounded-full bg-white/10 text-ink-100 ring-1 ring-white/15 transition hover:bg-white/15">
<X className="h-4 w-4" />
</button>
</div>
</div>
)}
</div>
);
}
export function TiltGalleryDemo() {
return (
<div className="mx-auto w-full max-w-3xl">
<TiltGallery />
</div>
);
}components/niceui/gallery/art.ts
/*
* Procedural artwork for the gallery demos: soft landscapes and abstract mesh
* gradients with film grain, rendered once to data URLs. Swap `src` for real
* photos in your app — every gallery component just takes image URLs.
*/
export type Artwork = { id: number; title: string; artist: string; place: string; year: number; tone: 'warm' | 'cool' | 'dusk' | 'mono' };
const PALETTES: string[][] = [
['#0b1d3a', '#1f4e79', '#f2a65a', '#f7d9a8'],
['#120c26', '#4b2a77', '#e66b9d', '#ffd1b3'],
['#06222b', '#0f5f6b', '#7fd1c7', '#e8f6f1'],
['#1b1410', '#5b3a26', '#d98c4a', '#f6e1c3'],
['#0e0f13', '#2b2f3a', '#8a93a6', '#e6e8ee'],
['#0a1a12', '#1f5134', '#9cc98a', '#f1f7da'],
['#1a0f14', '#6b1f3a', '#ef6f5e', '#ffd8a8'],
['#071426', '#123f73', '#5aa9e6', '#d6ecff'],
['#191325', '#3b2d5c', '#b39ddb', '#f3e9ff'],
['#201608', '#6e4a12', '#e0b34a', '#fff1c4'],
['#0b1216', '#29424f', '#6fa3b8', '#f0e6d2'],
['#170b0b', '#4a1414', '#c84b31', '#f5c26b'],
];
export const ARTWORKS: Artwork[] = [
{ id: 0, title: 'Low Tide, Dawn', artist: 'Mira Okafor', place: 'Comporta', year: 2025, tone: 'warm' },
{ id: 1, title: 'Neon Bloom', artist: 'Ilya Varga', place: 'Kyoto', year: 2024, tone: 'dusk' },
{ id: 2, title: 'Glass Lagoon', artist: 'Sana Iqbal', place: 'Faroe Islands', year: 2025, tone: 'cool' },
{ id: 3, title: 'Copper Dunes', artist: 'Teo Marchetti', place: 'Merzouga', year: 2023, tone: 'warm' },
{ id: 4, title: 'Fog Study No. 4', artist: 'Lena Brandt', place: 'Dolomites', year: 2024, tone: 'mono' },
{ id: 5, title: 'Green Hour', artist: 'Ravi Menon', place: 'Munnar', year: 2025, tone: 'cool' },
{ id: 6, title: 'Ember Coast', artist: 'Noor Haddad', place: 'Big Sur', year: 2024, tone: 'warm' },
{ id: 7, title: 'Blue Hour Harbour', artist: 'Jonas Weber', place: 'Bergen', year: 2025, tone: 'cool' },
{ id: 8, title: 'Lavender Field', artist: 'Camille Roy', place: 'Valensole', year: 2023, tone: 'dusk' },
{ id: 9, title: 'Golden Ridge', artist: 'Aiko Tanaka', place: 'Hokkaido', year: 2025, tone: 'warm' },
{ id: 10, title: 'Salt Flats', artist: 'Diego Alvarez', place: 'Uyuni', year: 2024, tone: 'mono' },
{ id: 11, title: 'Red Canyon', artist: 'Hana Kobayashi', place: 'Arizona', year: 2025, tone: 'warm' },
];
let seedState = 1;
const rand = () => {
seedState = (seedState * 1664525 + 1013904223) >>> 0;
return seedState / 4294967296;
};
const cache = new Map<string, string>();
/** A deterministic artwork as a data URL. `kind` picks a landscape or an abstract mesh. */
export function artwork(id: number, w = 960, h = 640, kind: 'landscape' | 'mesh' = id % 3 === 1 ? 'mesh' : 'landscape'): string {
const key = `${id}-${w}-${h}-${kind}`;
const hit = cache.get(key);
if (hit) return hit;
if (typeof document === 'undefined') return '';
const c = document.createElement('canvas');
c.width = w;
c.height = h;
const g = c.getContext('2d');
if (!g) return '';
seedState = (id + 1) * 9973;
const [deep, mid, hot, light] = PALETTES[id % PALETTES.length];
const sky = g.createLinearGradient(0, 0, 0, h);
sky.addColorStop(0, deep);
sky.addColorStop(0.55, mid);
sky.addColorStop(1, kind === 'mesh' ? deep : hot);
g.fillStyle = sky;
g.fillRect(0, 0, w, h);
// soft light blobs
const blobs = kind === 'mesh' ? 6 : 3;
for (let i = 0; i < blobs; i++) {
const x = rand() * w;
const y = rand() * h * (kind === 'mesh' ? 1 : 0.6);
const r = (0.25 + rand() * 0.45) * Math.max(w, h);
const rg = g.createRadialGradient(x, y, 0, x, y, r);
rg.addColorStop(0, [hot, light, mid][i % 3] + 'cc');
rg.addColorStop(1, 'transparent');
g.globalCompositeOperation = 'screen';
g.fillStyle = rg;
g.fillRect(0, 0, w, h);
}
g.globalCompositeOperation = 'source-over';
if (kind === 'landscape') {
// sun
const sx = (0.25 + rand() * 0.5) * w;
const sy = h * (0.38 + rand() * 0.12);
const sr = Math.min(w, h) * (0.07 + rand() * 0.05);
const glow = g.createRadialGradient(sx, sy, 0, sx, sy, sr * 5);
glow.addColorStop(0, light + 'aa');
glow.addColorStop(1, 'transparent');
g.fillStyle = glow;
g.fillRect(0, 0, w, h);
g.fillStyle = light;
g.beginPath();
g.arc(sx, sy, sr, 0, Math.PI * 2);
g.fill();
// ridges, back to front
for (let layer = 0; layer < 4; layer++) {
const base = h * (0.5 + layer * 0.12);
const amp = h * (0.12 - layer * 0.02);
const f1 = 1.5 + rand() * 2;
const f2 = 4 + rand() * 4;
const ph = rand() * 10;
g.beginPath();
g.moveTo(0, h);
for (let x = 0; x <= w; x += 4) {
const u = x / w;
const y = base - amp * (0.6 * Math.sin(u * f1 * Math.PI + ph) + 0.3 * Math.sin(u * f2 * Math.PI + ph * 2) + 0.1 * Math.sin(u * 23 + ph));
g.lineTo(x, y);
}
g.lineTo(w, h);
g.closePath();
const t = layer / 3;
const lg = g.createLinearGradient(0, base - amp, 0, h);
lg.addColorStop(0, mix(mid, deep, 0.25 + t * 0.6));
lg.addColorStop(1, mix(deep, '#000000', t * 0.5));
g.fillStyle = lg;
g.globalAlpha = 0.92;
g.fill();
g.globalAlpha = 1;
}
} else {
// flowing ribbons
for (let i = 0; i < 3; i++) {
g.beginPath();
const y0 = h * (0.2 + rand() * 0.6);
g.moveTo(-50, y0);
g.bezierCurveTo(w * 0.3, y0 - h * (rand() - 0.5), w * 0.7, y0 + h * (rand() - 0.5), w + 50, y0 + h * (rand() - 0.5) * 0.6);
g.lineWidth = Math.min(w, h) * (0.08 + rand() * 0.12);
g.strokeStyle = [light, hot, mid][i] + '55';
g.filter = `blur(${Math.round(Math.min(w, h) * 0.04)}px)`;
g.stroke();
g.filter = 'none';
}
}
// vignette
const vg = g.createRadialGradient(w / 2, h / 2, Math.min(w, h) * 0.3, w / 2, h / 2, Math.max(w, h) * 0.75);
vg.addColorStop(0, 'transparent');
vg.addColorStop(1, 'rgba(0,0,0,0.45)');
g.fillStyle = vg;
g.fillRect(0, 0, w, h);
// film grain
const img = g.getImageData(0, 0, w, h);
const d = img.data;
for (let i = 0; i < d.length; i += 4) {
const n = (rand() - 0.5) * 18;
d[i] += n;
d[i + 1] += n;
d[i + 2] += n;
}
g.putImageData(img, 0, 0);
const url = c.toDataURL('image/jpeg', 0.86);
cache.set(key, url);
return url;
}
function mix(a: string, b: string, t: number) {
const pa = parseInt(a.slice(1), 16);
const pb = parseInt(b.slice(1), 16);
const ch = (s: number) => Math.round(((pa >> s) & 255) * (1 - t) + ((pb >> s) & 255) * t);
return `rgb(${ch(16)},${ch(8)},${ch(0)})`;
}