Backgrounds03 / 118
Depth Gallery
A parallax background made of photos floating at different depths. As you scroll, far images lag behind the page, soft and dim, while near ones sweep past large and sharp. The cursor tilts the whole field and hovering a photo lifts it. A pure background: put your section on top, or anything inside it stays pinned in view.
GSAP ScrollTriggerGSAP ScrollTriggerReal photosReal photosCursor tiltCursor tiltLive tweaksLive tweaksReduced-motion safeReduced-motion safe
Scroll the stageMove to tilt
Tweak
LIVELIVEParallax
1.00
1.00
Field
36
7
Look
6.0px
0.55
14px
Usage
Follows your tweaks.
usage.tsx
import { DepthGallery } from "@/components/inreact/depth-gallery";
const photos = ["/photos/1.jpg", "/photos/2.jpg", "/photos/3.jpg" /* … */];
export function Hero() {
return (
<DepthGallery
items={photos}
className="h-[220vh] w-full bg-black"
/>
);
}Install with the CLI
TS + Tailwind
npx shadcn@latest add https://inreact.vercel.app/r/depth-gallery.jsonOr copy the source
Install the dependencies, then save this as components/inreact/depth-gallery.tsx.
terminal
npm install gsapcomponents/inreact/depth-gallery.tsx
"use client";
import { gsap } from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
import { useEffect, useMemo, useRef, type ReactNode } from "react";
gsap.registerPlugin(ScrollTrigger);
/**
* Depth Gallery: a parallax background made of images floating at different
* depths.
*
* Far images are small, soft and dim; near ones are large and sharp. As the
* section scrolls, every layer moves at its own speed (far ones lag behind
* the page, near ones overtake it), so the field opens up in depth around
* your headline, which stays pinned in view. The cursor tilts the whole field
* (near images move more) and hovering an image lifts it.
*
* <DepthGallery items={["/a.jpg", "/b.jpg", "/c.jpg"]} className="h-[220vh]">
* <h1>Your headline</h1>
* </DepthGallery>
*
* GSAP + ScrollTrigger. The layout is seeded, so it is identical on every
* load. Reduced motion shows a still field.
*/
export type DepthGalleryItem = string | { src: string; alt?: string };
export interface DepthGalleryProps {
/** Images (URLs or { src, alt }). Repeated to fill `count` tiles. */
items: DepthGalleryItem[];
/** Foreground content, centred above the field. */
children?: ReactNode;
/** Number of tiles in the field. */
count?: number;
/** How far layers travel as you scroll (parallax strength). */
depth?: number;
/** How much the field tilts with the cursor. */
tilt?: number;
/** Blur of the farthest layer, in px. */
blur?: number;
/** How much far layers fade into the background (0 to 1). */
fog?: number;
/** Corner radius of the tiles, in px. */
radius?: number;
/** Change to reshuffle the layout. */
seed?: number;
/** Scroll container if the page does not scroll the window. */
scroller?: Element | null;
className?: string;
}
const isReducedMotion = () =>
typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
/** Deterministic random numbers. */
function rng(seed: number) {
let s = seed >>> 0;
return () => {
s = (s + 0x6d2b79f5) >>> 0;
let t = s;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
/**
* A soft, layered contact shadow: six stacked layers, each twice as far and
* twice as soft as the last, so it fades out smoothly with no visible edge.
* Far cards cast none; near cards float higher with a longer, lighter fall.
*/
function softShadow(d: number) {
if (d < 0.45) return "none"; // far cards sit in the haze and cast nothing
const lift = 0.5 + d * 1.5;
const a = ((d - 0.45) * 0.09).toFixed(3);
return [1, 2, 4, 8, 16, 32]
.map((k) => `0 ${(k * lift).toFixed(1)}px ${(k * lift * 2).toFixed(1)}px rgba(0,0,0,${a})`)
.join(", ");
}
type Tile = { src: string; alt: string; d: number; x: number; y: number; w: number; tilt: number };
/** Scatter tiles over the field: spread by columns, deeper ones smaller, near ones kept off the centre. */
function layout(items: DepthGalleryItem[], count: number, seed: number, clearCentre: boolean): Tile[] {
const r = rng(seed);
const list = items.map((it) => (typeof it === "string" ? { src: it, alt: "" } : { src: it.src, alt: it.alt ?? "" }));
if (!list.length) return [];
const cols = 6;
const tiles: Tile[] = [];
for (let i = 0; i < count; i++) {
const it = list[i % list.length];
const d = (i % 5) / 4 * 0.85 + r() * 0.15; // spread evenly over five depth bands
let x = ((i % cols) + 0.15 + r() * 0.7) / cols; // 0..1
const y = -0.15 + r() * 1.3; // a little beyond the edges, scroll brings them in
const w = 0.11 + d * 0.19;
// near tiles frame the headline instead of covering it: keep their whole width out of the middle
const clear = 0.16 + w / 2;
if (clearCentre && d > 0.45 && Math.abs(x - 0.5) < clear) x = x < 0.5 ? 0.5 - clear - r() * 0.08 : 0.5 + clear + r() * 0.08;
tiles.push({ ...it, d, x, y, w, tilt: (r() - 0.5) * 6 });
}
return tiles.sort((a, b) => a.d - b.d); // far first, so near tiles paint on top
}
export function DepthGallery({
items,
children,
count = 36,
depth = 1,
tilt = 1,
blur = 6,
fog = 0.55,
radius = 14,
seed = 7,
scroller,
className,
}: DepthGalleryProps) {
const hostRef = useRef<HTMLDivElement>(null);
const hasContent = Boolean(children);
const tiles = useMemo(() => layout(items, count, seed, hasContent), [items, count, seed, hasContent]);
const depthRef = useRef(depth);
const tiltRef = useRef(tilt);
useEffect(() => {
depthRef.current = depth;
tiltRef.current = tilt;
}, [depth, tilt]);
useEffect(() => {
const host = hostRef.current;
if (!host) return;
if (getComputedStyle(host).position === "static") host.style.position = "relative";
const still = isReducedMotion();
const outers = Array.from(host.querySelectorAll<HTMLElement>("[data-tile]"));
const inners = outers.map((o) => o.firstElementChild as HTMLElement);
const ds = outers.map((o) => Number(o.dataset.d));
const frames = outers.map((o) => o.querySelector<HTMLElement>("[data-frame]")!);
const imgs = outers.map((o) => o.querySelector<HTMLImageElement>("img")!);
// centre each tile on its point (GSAP owns these transforms, so no CSS translate)
gsap.set(outers, { xPercent: -50, yPercent: -50 });
// a frame only appears once its photo has loaded, so there is never an empty box or a lone shadow
const shown = (i: number) => frames[i].setAttribute("data-loaded", "");
const offLoad = imgs.map((img, i) => {
if (img.complete && img.naturalWidth) {
shown(i);
return () => {};
}
const on = () => shown(i);
img.addEventListener("load", on, { once: true });
return () => img.removeEventListener("load", on);
});
// entrance: far layers settle in first, near ones last
const intro = still
? null
: gsap.fromTo(
inners,
{ autoAlpha: 0, scale: 0.86 },
{ autoAlpha: 1, scale: 1, duration: 1.4, ease: "expo.out", stagger: { each: 0.035 } },
);
if (still)
return () => {
intro?.kill();
offLoad.forEach((f) => f());
};
// scroll: each layer travels by its depth; near layers sweep past, far ones barely move
const travel = () => host.offsetHeight * 0.55 * depthRef.current;
const tl = gsap.timeline({
defaults: { ease: "none" },
scrollTrigger: {
trigger: host,
scroller: scroller ?? undefined,
start: "top bottom",
end: "bottom top",
scrub: 0.8,
invalidateOnRefresh: true,
},
});
gsap.set(imgs, { scale: 1.2 });
outers.forEach((o, i) => {
// far layers lag behind the page (they drift down), near layers overtake it
const f = ds[i] * 1.3 - 0.45;
tl.fromTo(
o,
{ y: () => travel() * f * 0.5, scale: 1 - ds[i] * 0.08 },
{ y: () => -travel() * f * 0.5, scale: 1 + ds[i] * 0.1 },
0,
);
// and inside each frame the photo drifts the other way, like looking through a window
tl.fromTo(imgs[i], { yPercent: -7 }, { yPercent: 7 }, 0);
});
// scroll speed: fast flicks bend the near cards like they are rushing past, then they spring back
const skews = inners.map((el) => gsap.quickTo(el, "skewY", { duration: 0.7, ease: "power3" }));
const settle = gsap.delayedCall(0.14, () => skews.forEach((q) => q(0))).pause();
const onSpeed = () => {
const v = tl.scrollTrigger!.getVelocity();
const k = gsap.utils.clamp(-1, 1, v / 2400);
skews.forEach((q, i) => q(-k * (1 + ds[i] * 6)));
settle.restart(true);
};
const target: EventTarget = scroller ?? window;
target.addEventListener("scroll", onSpeed, { passive: true });
// cursor: the field tilts toward you; near tiles move more
const xs = inners.map((el) => gsap.quickTo(el, "x", { duration: 1.1, ease: "power3" }));
const ys = inners.map((el) => gsap.quickTo(el, "y", { duration: 1.1, ease: "power3" }));
const rs = inners.map((el) => gsap.quickTo(el, "rotation", { duration: 1.1, ease: "power3" }));
const move = (e: PointerEvent) => {
const r = host.getBoundingClientRect();
const px = (e.clientX - r.left) / r.width - 0.5;
const py = (e.clientY - r.top) / r.height - 0.5;
const k = tiltRef.current;
inners.forEach((_, i) => {
const d = ds[i];
xs[i](-px * (20 + d * 90) * k);
ys[i](-py * (14 + d * 60) * k);
rs[i](px * d * 4 * k);
});
};
const leave = () => {
inners.forEach((_, i) => {
xs[i](0);
ys[i](0);
rs[i](0);
});
};
host.addEventListener("pointermove", move);
host.addEventListener("pointerleave", leave);
// the headline stays centred in the visible window while the field flows past
const view = () =>
host.style.setProperty("--dg-view", `${scroller ? scroller.clientHeight : window.innerHeight}px`);
view();
window.addEventListener("resize", view);
// size changes: let ScrollTrigger re-measure
const ro = new ResizeObserver(() => {
view();
ScrollTrigger.refresh();
});
ro.observe(host);
if (scroller) ro.observe(scroller);
return () => {
intro?.kill();
offLoad.forEach((f) => f());
target.removeEventListener("scroll", onSpeed);
settle.kill();
tl.scrollTrigger?.kill();
tl.kill();
host.removeEventListener("pointermove", move);
host.removeEventListener("pointerleave", leave);
ro.disconnect();
window.removeEventListener("resize", view);
gsap.killTweensOf(inners);
gsap.set(imgs, { clearProps: "transform" });
};
}, [tiles, scroller]);
return (
<div ref={hostRef} className={["isolate overflow-clip", className].filter(Boolean).join(" ")}>
<div aria-hidden={children ? true : undefined} className="absolute inset-0">
{tiles.map((t, i) => (
<div
key={i}
data-tile
data-d={t.d}
className="absolute"
style={{
left: `${t.x * 100}%`,
top: `${t.y * 100}%`,
width: `${t.w * 100}%`,
zIndex: Math.round(t.d * 10),
}}
>
<div>
{/* hover lifts the tile a touch. Depth is haze, not darkness: far cards fade
into the background and soften, so none of them reads as a dark slab */}
<div
className="transition-transform duration-700 ease-[cubic-bezier(0.16,1,0.3,1)] hover:-translate-y-1.5 hover:scale-[1.04]"
style={{
rotate: `${t.tilt}deg`,
opacity: 1 - (1 - t.d) ** 2 * fog, // only the far back fades; mid cards stay solid
filter: t.d < 0.98 ? `blur(${((1 - t.d) * blur).toFixed(2)}px)` : undefined,
}}
>
<div
data-frame
className="overflow-hidden opacity-0 transition-opacity duration-700 data-[loaded]:opacity-100"
style={{ borderRadius: radius, boxShadow: softShadow(t.d) }}
>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={t.src}
alt={t.alt}
loading="lazy"
decoding="async"
draggable={false}
className="block aspect-[3/4] w-full object-cover select-none"
/>
</div>
</div>
</div>
</div>
))}
</div>
{children && (
<div className="pointer-events-none absolute inset-0 z-20">
<div className="sticky top-0 grid h-[var(--dg-view,100vh)] max-h-full place-items-center">
<div className="pointer-events-auto">{children}</div>
</div>
</div>
)}
</div>
);
}
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
11 propsitems(string | { src, alt })[]Your images. Repeated to fill the field.childrenReactNodeOptional content, pinned in the middle of the view while the field scrolls past. Near photos keep clear of it.countnumberNumber of photos in the field.default 36default 36depthnumberParallax strength: how far the layers travel against each other as you scroll.default 1default 1tiltnumberHow much the field follows the cursor. 0 turns it off.default 1default 1blurnumberBlur of the farthest layer, in px.default 6default 6fognumberHow much far layers fade into the background, 0 to 1.default 0.55default 0.55radiusnumberCorner radius of the photos, in px.default 14default 14seednumberChange it to reshuffle the layout.default 7default 7scrollerElement | nullScroll container, if the page does not scroll the window.classNamestringSize it. Make it taller than the screen, e.g. h-[220vh] w-full.