← All components Next componentDepth Tunnel→
Gallery · Grid
Perspective Grid
An infinite tilted wall of images you drag to pan in any direction; hovered cards lift out of it.
<InfinitePerspectiveGrid />Live
Drag to pan · hover to lift
Customize
Installation
Use it in your project
Or skip the copy-paste
One command: writes the file and installs the dependencies.
$ npx deepui-cli add perspective-grid
01
Install
The 3D packages this component is built on.
$ npm install three @react-three/fiber @react-three/drei && npm install -D @types/three
02
Add the component
One self-contained file: create components/InfinitePerspectiveGrid.tsx and paste it in.
components/InfinitePerspectiveGrid.tsx
1"use client";23import {4 Component,5 memo,6 Suspense,7 useCallback,8 useEffect,9 useLayoutEffect,10 useMemo,11 useRef,12 useState,13 type CSSProperties,14 type ReactNode,15 type Ref,16 type RefObject,17} from "react";18import * as THREE from "three";19import {20 Canvas,21 useFrame,22 useThree,23 type CanvasProps,24 type ThreeElements,25 type ThreeEvent,26} from "@react-three/fiber";27import { useTexture } from "@react-three/drei";2829/**30 * The shared props API of DeepUI's individual 3D components (not the full-page templates, which keep31 * their own tailored scenes).32 *33 * The props are grouped by concern. A component extends ONLY the groups it really applies, so its34 * type never advertises a knob that does nothing (a card has no particles, a background has no tilt):35 *36 * interface MyCardProps extends CursorProps, TiltProps, MaterialProps, PerformanceProps { … }37 *38 * `Base3DComponentProps` is every group at once, for tooling that handles any component. Same name,39 * same unit and same meaning everywhere; the default values live in DEFAULT_3D_PROPS. These files are40 * inlined into each component's single-file bundle (lib/bundle-source.mjs), only what it uses.41 */4243/** Which rotation axes follow the pointer. "x-only": the object nods (up / down); "y-only": it turns (left / right). */44export type TiltAxis = "both" | "x-only" | "y-only" | "none";4546/** 1. Cursor: how the pointer pulls, pushes and drags the object. */47interface CursorProps {48 /** Reach of the pointer's influence, in the component's own space: CSS pixels for pixel-laid-out widgets, world units for 3D scenes (each component says which). Default 220 (px). */49 cursorRadius?: number;50 /** Positive pulls things towards the pointer, negative pushes them away (repulsion, shockwave). Default 1. */51 cursorForce?: number;52 /** How far the object slides towards the pointer, 0 (stays put) to 1 (follows closely). Default 0. */53 magneticStrength?: number;54 /** Share of the remaining distance the motion closes each frame (at 60 fps), 0.01 (heavy, slow) to 1 (instant). Default 0.1. */55 cursorDamping?: number;56}5758/** 2. Tilt and parallax: the object leans towards the pointer, its layers slide against each other. */59interface TiltProps {60 /** Largest lean towards the pointer, in degrees. Default 15. */61 maxTiltAngle?: number;62 /** Axes that follow the pointer. Default "both". */63 tiltAxis?: TiltAxis;64 /** Lean away from the pointer instead of towards it. Default false. */65 invertTilt?: boolean;66 /** How far apart the depth layers slide when the object tilts, 0 (flat) to 2. Default 1. */67 parallaxOffset?: number;68}6970/** 3. Text and 3D typography, for components that draw a label. */71interface Text3DProps {72 /** The label drawn by the component. */73 text?: string;74 /** Scale of the lettering. Default 1. */75 fontSize?: number;76 /** Extrusion depth of 3D letters. Default 0.2. */77 textDepth?: number;78 /** Bevelled, light-catching edges on 3D letters. Default true. */79 bevelEnabled?: boolean;80 /** Custom font: a .woff / .ttf (flat text) or a typeface .json (extruded text). */81 fontUrl?: string;82}8384/** 4. Rendering, materials and glow. */85interface MaterialProps {86 /** Main color of the object. Default "#6366f1". */87 primaryColor?: string;88 /** Color of the glow. Default "#00f0ff". */89 emissiveColor?: string;90 /** Strength of the glow, 0 (none) to 3. Default 1. */91 emissiveIntensity?: number;92 /** 0 (mirror, glass) to 1 (matte). Default 0.3. */93 roughness?: number;94 /** 0 (plastic, organic) to 1 (metal). Default 0.5. */95 metalness?: number;96 /** 0 (opaque) to 1 (clear glass): see-through, refracting surfaces. Default 0. */97 transmission?: number;98 /** Technical wireframe rendering. Default false. */99 wireframe?: boolean;100}101102/** 5. Particles, idle motion and shader animation. */103interface MotionProps {104 /** Number of instanced elements. Default depends on the component. */105 particleCount?: number;106 /** Spin on its own, in radians per second (negative: the other way; 0.5 ≈ one turn in 12 s). Default 0. */107 autoRotateSpeed?: number;108 /** Pulses or ripples per second. Default 1. */109 pulseRate?: number;110 /** Amplitude of the noise deformation, 0 (none) to 2. Default 1. */111 displacementScale?: number;112}113114/** 6. Environment and camera. */115interface EnvironmentProps {116 /** Camera field of view, in degrees. Default depends on the component. */117 cameraFov?: number;118 /** Color of the depth fog. Default "#0a0a0a". */119 fogColor?: string;120 /** Thickness of the fog, 0 (none) to 0.2. Default 0. */121 fogDensity?: number;122}123124/** 7. Performance and accessibility. */125interface PerformanceProps {126 /** Lighter rendering for weak devices: pixel ratio 1, fewer instances, smaller environment maps. Default false. */127 lowPowerMode?: boolean;128 /** Under the OS "reduce motion" setting, stop idle spin, pulses and deformation (pointer feedback stays). Default true. */129 respectReducedMotion?: boolean;130 /** Stop the render loop while the component is scrolled out of view. Default true. */131 pauseWhenOffscreen?: boolean;132}133134/** Every group at once. Components extend only the groups they apply (see the top of this file). */135interface Base3DComponentProps136 extends CursorProps,137 TiltProps,138 Text3DProps,139 MaterialProps,140 MotionProps,141 EnvironmentProps,142 PerformanceProps {}143144type Defaults = Required<Omit<Base3DComponentProps, "text" | "fontUrl" | "particleCount" | "cameraFov">>;145146/** The values a prop takes when it is left out. A component may override one, and then documents it. */147const DEFAULT_3D_PROPS: Defaults = {148 cursorRadius: 220,149 cursorForce: 1,150 magneticStrength: 0,151 cursorDamping: 0.1,152 maxTiltAngle: 15,153 tiltAxis: "both",154 invertTilt: false,155 parallaxOffset: 1,156 fontSize: 1,157 textDepth: 0.2,158 bevelEnabled: true,159 primaryColor: "#6366f1",160 emissiveColor: "#00f0ff",161 emissiveIntensity: 1,162 roughness: 0.3,163 metalness: 0.5,164 transmission: 0,165 wireframe: false,166 autoRotateSpeed: 0,167 pulseRate: 1,168 displacementScale: 1,169 fogColor: "#0a0a0a",170 fogDensity: 0,171 lowPowerMode: false,172 respectReducedMotion: true,173 pauseWhenOffscreen: true,174};175176/** Fills the positioned parent. Unlike the backgrounds, galleries receive pointer events. */177const GALLERY_STYLE: CSSProperties = {178 position: "absolute",179 top: 0,180 left: 0,181 width: "100%",182 height: "100%",183};184185interface GalleryCanvasProps extends Omit<CanvasProps, "children" | "style" | "frameloop" | "gl">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {186 children: ReactNode;187 /**188 * The gallery uses the wheel: Lenis (site-wide smooth scroll) is told to leave wheel events189 * over the canvas alone, so the gallery's own handler decides whether the page scrolls.190 */191 captureWheel?: boolean;192 /** CSS touch-action of the canvas: "pan-y" keeps vertical page scrolling on touch screens. */193 touchAction?: CSSProperties["touchAction"];194}195196/**197 * Ready-to-use <Canvas> shared by every gallery: the render loop pauses while the gallery is198 * scrolled out of view, and R3F disposes the renderer and its WebGL context on unmount.199 */200function GalleryCanvas({ children, captureWheel = false, touchAction = "pan-y", dpr = [1, 2], pauseWhenOffscreen = DEFAULT_3D_PROPS.pauseWhenOffscreen, lowPowerMode = DEFAULT_3D_PROPS.lowPowerMode, ...canvasProps }: GalleryCanvasProps) {201 const containerRef = useRef<HTMLDivElement>(null);202 const [inView, setInView] = useState(true);203204 useEffect(() => {205 const el = containerRef.current;206 if (!el) return undefined;207 const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting));208 observer.observe(el);209 return () => observer.disconnect();210 }, []);211212 return (213 <div ref={containerRef} style={GALLERY_STYLE} {...(captureWheel ? { "data-lenis-prevent": "" } : {})}>214 <Canvas215 dpr={lowPowerMode ? 1 : dpr}216 frameloop={inView || !pauseWhenOffscreen ? "always" : "never"}217 gl={{ antialias: true, alpha: true, powerPreference: "high-performance" }}218 style={{ touchAction }}219 {...canvasProps}220 >221 {children}222 </Canvas>223 </div>224 );225}226227interface DragHandlers {228 /** false: the canvas ignores drags (no grab cursor). Default true. */229 enabled?: boolean;230 onStart?: () => void;231 /** Movement since the previous event, in CSS pixels. */232 onMove: (dx: number, dy: number) => void;233 /** Release velocity, in CSS pixels per second (for inertia). */234 onEnd?: (vx: number, vy: number) => void;235}236237/** Drag on the canvas (mouse, pen or touch), with release velocity for inertia. */238function useCanvasDrag(handlers: DragHandlers) {239 const gl = useThree((state) => state.gl);240 const handlersRef = useRef(handlers);241 useEffect(() => {242 handlersRef.current = handlers;243 });244245 useEffect(() => {246 const el = gl.domElement;247 let pointerId: number | null = null;248 let lastX = 0;249 let lastY = 0;250 let lastTime = 0;251 let vx = 0;252 let vy = 0;253 const grab = () => (handlersRef.current.enabled === false ? "" : "grab");254 el.style.cursor = grab();255256 const down = (event: PointerEvent) => {257 if (event.button !== 0 || pointerId !== null || handlersRef.current.enabled === false) return;258 pointerId = event.pointerId;259 lastX = event.clientX;260 lastY = event.clientY;261 lastTime = performance.now();262 vx = 0;263 vy = 0;264 el.style.cursor = "grabbing";265 handlersRef.current.onStart?.();266 };267 const move = (event: PointerEvent) => {268 if (event.pointerId !== pointerId) return;269 const now = performance.now();270 const dt = Math.max(1, now - lastTime) / 1000;271 const dx = event.clientX - lastX;272 const dy = event.clientY - lastY;273 // Smoothed velocity: a single jittery event at release must not decide the inertia274 vx = vx * 0.6 + (dx / dt) * 0.4;275 vy = vy * 0.6 + (dy / dt) * 0.4;276 lastX = event.clientX;277 lastY = event.clientY;278 lastTime = now;279 handlersRef.current.onMove(dx, dy);280 };281 const up = (event: PointerEvent) => {282 if (event.pointerId !== pointerId) return;283 pointerId = null;284 el.style.cursor = grab();285 // A pause before releasing means no throw286 const idle = performance.now() - lastTime > 80;287 handlersRef.current.onEnd?.(idle ? 0 : vx, idle ? 0 : vy);288 };289290 el.addEventListener("pointerdown", down);291 window.addEventListener("pointermove", move, { passive: true });292 window.addEventListener("pointerup", up);293 window.addEventListener("pointercancel", up);294 return () => {295 el.removeEventListener("pointerdown", down);296 window.removeEventListener("pointermove", move);297 window.removeEventListener("pointerup", up);298 window.removeEventListener("pointercancel", up);299 el.style.cursor = "";300 };301 }, [gl]);302}303304/**305 * Collects the textures loaded by a gallery's cards and disposes them (plus drei's loader cache306 * entries) when the gallery unmounts or its image list changes.307 */308function useGalleryTextures(urls: string[]) {309 const textures = useRef(new Set<THREE.Texture>());310 const key = urls.join("\n");311 const onTexture = useCallback((texture: THREE.Texture) => {312 textures.current.add(texture);313 }, []);314315 useEffect(() => {316 const loaded = textures.current;317 return () => {318 loaded.forEach((texture) => texture.dispose());319 loaded.clear();320 const list = key ? key.split("\n") : [];321 if (list.length) useTexture.clear(list);322 };323 }, [key]);324325 return onTexture;326}327328const cardVertexShader = /* glsl */ `329uniform float uCurve; // 1 / radius: bends the card around the Y axis, convex side out (0 = flat)330331varying vec2 vUv;332varying float vFacing;333334void main() {335 vUv = uv;336 vec3 p = position;337 vec3 n = vec3(0.0, 0.0, 1.0);338 if (uCurve > 0.0001) {339 float a = p.x * uCurve;340 p.x = sin(a) / uCurve;341 p.z = (cos(a) - 1.0) / uCurve;342 n = vec3(sin(a), 0.0, cos(a));343 }344 vec4 mvPosition = modelViewMatrix * vec4(p, 1.0);345 vFacing = abs(dot(normalize(normalMatrix * n), normalize(-mvPosition.xyz)));346 gl_Position = projectionMatrix * mvPosition;347}348`;349350const cardFragmentShader = /* glsl */ `351uniform sampler2D uMap;352uniform float uHasMap; // 1 once the texture is loaded353uniform float uReveal; // 0 → 1 fade from the placeholder to the image354uniform float uImageAspect;355uniform vec2 uSize; // card size in world units356uniform float uRadius; // corner radius in world units357uniform float uZoom; // > 1 crops into the image (headroom for parallax)358uniform vec2 uOffset; // image shift inside the card (parallax), in UV units359uniform float uBlur; // motion blur length, in UV units360uniform vec2 uBlurDir;361uniform float uOpacity;362uniform float uDim; // 0 = full brightness, 1 = black363uniform float uHover; // 0 → 1 highlight364uniform float uShade; // how much faces turned away from the camera darken365uniform float uTime;366uniform vec3 uTint; // placeholder color367368varying vec2 vUv;369varying float vFacing;370371// "object-fit: cover": the image fills the card without stretching372vec2 coverUv(vec2 uv) {373 float planeAspect = uSize.x / uSize.y;374 vec2 scale = planeAspect > uImageAspect ? vec2(1.0, uImageAspect / planeAspect) : vec2(planeAspect / uImageAspect, 1.0);375 return (uv - 0.5) * scale / uZoom + 0.5 + uOffset;376}377378float roundedMask(vec2 uv) {379 vec2 p = (uv - 0.5) * uSize;380 vec2 q = abs(p) - (uSize * 0.5 - uRadius);381 float d = length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - uRadius;382 float aa = fwidth(d);383 return 1.0 - smoothstep(-aa, aa, d);384}385386void main() {387 vec2 uv = vUv;388 // Seen from behind (a ring's far side), the image would be mirrored: flip it back389 if (!gl_FrontFacing) uv.x = 1.0 - uv.x;390391 float mask = roundedMask(vUv);392 float alpha = mask * uOpacity;393 if (alpha < 0.005) discard;394395 // Placeholder: dark tint with a sweeping shimmer while the texture loads396 float shimmer = pow(max(0.0, sin((vUv.x - vUv.y * 0.5) * 3.0 - uTime * 2.5)), 12.0);397 vec3 color = uTint + shimmer * 0.06;398399 if (uHasMap > 0.5) {400 vec2 imageUv = coverUv(uv);401 vec3 image;402 if (uBlur > 0.0005) {403 // Motion blur: 7 taps along the direction of travel404 image = vec3(0.0);405 for (int i = 0; i < 7; i++) {406 float t = (float(i) / 6.0 - 0.5) * uBlur;407 image += texture2D(uMap, imageUv + uBlurDir * t).rgb;408 }409 image /= 7.0;410 } else {411 image = texture2D(uMap, imageUv).rgb;412 }413 color = mix(color, image, uReveal);414 }415416 color *= mix(1.0, 0.35 + 0.65 * vFacing, uShade);417 color *= 1.0 - uDim;418 color += uHover * 0.07;419 gl_FragColor = vec4(color, alpha);420 #include <colorspace_fragment>421}422`;423424interface CardUniforms {425 uMap: THREE.IUniform<THREE.Texture | null>;426 uHasMap: THREE.IUniform<number>;427 uReveal: THREE.IUniform<number>;428 uImageAspect: THREE.IUniform<number>;429 uSize: THREE.IUniform<THREE.Vector2>;430 uRadius: THREE.IUniform<number>;431 uCurve: THREE.IUniform<number>;432 uZoom: THREE.IUniform<number>;433 uOffset: THREE.IUniform<THREE.Vector2>;434 uBlur: THREE.IUniform<number>;435 uBlurDir: THREE.IUniform<THREE.Vector2>;436 uOpacity: THREE.IUniform<number>;437 uDim: THREE.IUniform<number>;438 uHover: THREE.IUniform<number>;439 uShade: THREE.IUniform<number>;440 uTime: THREE.IUniform<number>;441 uTint: THREE.IUniform<THREE.Color>;442}443444function createCardMaterial() {445 const uniforms: CardUniforms = {446 uMap: { value: null },447 uHasMap: { value: 0 },448 uReveal: { value: 0 },449 uImageAspect: { value: 1 },450 uSize: { value: new THREE.Vector2(1, 1) },451 uRadius: { value: 0.06 },452 uCurve: { value: 0 },453 uZoom: { value: 1 },454 uOffset: { value: new THREE.Vector2() },455 uBlur: { value: 0 },456 uBlurDir: { value: new THREE.Vector2(0, 1) },457 uOpacity: { value: 1 },458 uDim: { value: 0 },459 uHover: { value: 0 },460 uShade: { value: 0 },461 uTime: { value: 0 },462 uTint: { value: new THREE.Color() },463 };464 return new THREE.ShaderMaterial({465 uniforms: uniforms as unknown as Record<string, THREE.IUniform>,466 vertexShader: cardVertexShader,467 fragmentShader: cardFragmentShader,468 transparent: true,469 side: THREE.DoubleSide,470 });471}472473/** Typed access to a card's uniforms from its mesh (galleries animate them in useFrame). */474function cardUniforms(mesh: THREE.Mesh) {475 return (mesh.material as THREE.ShaderMaterial).uniforms as unknown as CardUniforms;476}477478/** Plane sized in world units; enough columns to bend smoothly when the card is curved. */479function createCardGeometry(width: number, height: number, segments = 1) {480 return new THREE.PlaneGeometry(width, height, segments, 1);481}482483function TextureBinder({ url, material, onTexture }: { url: string; material: THREE.ShaderMaterial; onTexture?: (texture: THREE.Texture) => void }) {484 const texture = useTexture(url); // suspends until loaded; drei caches it per URL485 useLayoutEffect(() => {486 if (texture.colorSpace !== THREE.SRGBColorSpace) {487 texture.colorSpace = THREE.SRGBColorSpace;488 texture.needsUpdate = true;489 }490 texture.anisotropy = 4;491 const image = texture.image as { width?: number; height?: number } | undefined;492 const u = material.uniforms as unknown as CardUniforms;493 if (u.uMap.value !== texture) u.uReveal.value = 0; // fade in each new image494 u.uMap.value = texture;495 u.uImageAspect.value = image?.width && image?.height ? image.width / image.height : 1;496 u.uHasMap.value = 1;497 onTexture?.(texture);498 }, [texture, material, onTexture]);499 return null;500}501502/** A failed image keeps its placeholder instead of breaking the whole gallery. */503class TextureErrorBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {504 state = { failed: false };505 static getDerivedStateFromError() {506 return { failed: true };507 }508 render() {509 return this.state.failed ? null : this.props.children;510 }511}512513interface ImageCardProps extends Omit<ThreeElements["mesh"], "geometry" | "material" | "ref"> {514 url: string;515 width: number;516 height: number;517 /** Shared plane from createCardGeometry(width, height, segments). */518 geometry: THREE.BufferGeometry;519 radius?: number;520 /** 1 / radius of the surface the card is bent on (0 = flat). */521 curve?: number;522 /** 0–1: darken the card as it turns away from the camera. */523 shade?: number;524 zoom?: number;525 placeholderColor?: string;526 onTexture?: (texture: THREE.Texture) => void;527 ref?: Ref<THREE.Mesh>;528}529530/**531 * Image card: rounded corners, cover-fit image, placeholder shimmer while loading, fade-in once532 * loaded, placeholder kept if the image fails. Its material is created once and disposed on unmount.533 */534const ImageCard = memo(function ImageCard({535 url,536 width,537 height,538 geometry,539 radius = 0.06,540 curve = 0,541 shade = 0,542 zoom = 1,543 placeholderColor = "#151517",544 onTexture,545 ref,546 ...meshProps547}: ImageCardProps) {548 const material = useMemo(() => createCardMaterial(), []);549 const u = material.uniforms as unknown as CardUniforms;550551 useEffect(() => {552 u.uSize.value.set(width, height);553 u.uRadius.value = Math.min(radius, width / 2, height / 2);554 u.uCurve.value = curve;555 u.uShade.value = shade;556 u.uZoom.value = zoom;557 u.uTint.value.set(placeholderColor);558 }, [u, width, height, radius, curve, shade, zoom, placeholderColor]);559560 useEffect(() => () => material.dispose(), [material]);561562 useFrame((state, delta) => {563 if (u.uHasMap.value > 0.5) {564 if (u.uReveal.value < 0.999) u.uReveal.value = THREE.MathUtils.damp(u.uReveal.value, 1, 5, delta);565 } else {566 u.uTime.value = state.clock.elapsedTime;567 }568 });569570 return (571 // The shader bends the card: the plane's own bounds are not reliable for frustum culling572 <mesh ref={ref} geometry={geometry} material={material} frustumCulled={false} {...meshProps}>573 <TextureErrorBoundary key={url}>574 <Suspense fallback={null}>575 <TextureBinder url={url} material={material} onTexture={onTexture} />576 </Suspense>577 </TextureErrorBoundary>578 </mesh>579 );580});581582export interface PerspectiveGridProps extends Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {583 images: string[];584 /** Columns × rows of recycled card slots. Enough to cover the view; the grid itself is infinite. Default [9, 9]. */585 gridSize?: [number, number];586 /** Tilt of the wall, in degrees. Default 32. */587 tiltAngle?: number;588 /** Space between cards, in world units. Default 0.25. */589 gap?: number;590 /** How far a hovered card lifts out of the wall. Default 0.6. */591 hoverElevation?: number;592}593594const CARD_WIDTH = 1.7;595const CARD_HEIGHT = 2.2;596const PARALLAX = 0.09; // image shift inside the card, relative to its position on the wall597598/** Wraps v into [-span/2, span/2). */599function wrap(v: number, span: number) {600 return ((((v + span / 2) % span) + span) % span) - span / 2;601}602603/** Deterministic image for an infinite-grid cell, scrambled so neighbors rarely repeat. */604function cellImage(cx: number, cy: number, count: number) {605 let h = Math.imul(cx, 374761393) + Math.imul(cy, 668265263);606 h = Math.imul(h ^ (h >>> 13), 1274126177);607 return Math.abs(h ^ (h >>> 16)) % count;608}609610interface Pan {611 x: number;612 y: number;613 tx: number;614 ty: number;615 vx: number;616 vy: number;617}618619interface SlotProps {620 col: number;621 row: number;622 cols: number;623 rows: number;624 cellW: number;625 cellH: number;626 images: string[];627 pan: RefObject<Pan>;628 hovered: RefObject<string>;629 geometry: THREE.BufferGeometry;630 tilt: number;631 hoverElevation: number;632 onTexture: (texture: THREE.Texture) => void;633}634635/** One recycled card: it wraps around when it leaves the grid and takes the image of its new cell. */636const Slot = memo(function Slot({ col, row, cols, rows, cellW, cellH, images, pan, hovered, geometry, tilt, hoverElevation, onTexture }: SlotProps) {637 const meshRef = useRef<THREE.Mesh>(null);638 const id = `${col}:${row}`;639 const spanW = cols * cellW;640 const spanH = rows * cellH;641 const baseX = (col - (cols - 1) / 2) * cellW;642 const baseY = (row - (rows - 1) / 2) * cellH;643 const [cell, setCell] = useState<[number, number]>(() => [Math.round(baseX / cellW), Math.round(baseY / cellH)]);644645 useFrame((_, delta) => {646 const mesh = meshRef.current;647 if (!mesh) return;648 const p = pan.current;649 const x = wrap(baseX + p.x, spanW);650 const y = wrap(baseY + p.y, spanH);651652 // Which cell of the infinite grid this slot shows right now653 const cx = Math.round((x - p.x) / cellW);654 const cy = Math.round((y - p.y) / cellH);655 if (cx !== cell[0] || cy !== cell[1]) setCell([cx, cy]);656657 const u = cardUniforms(mesh);658 const isHovered = hovered.current === id;659 const lift = THREE.MathUtils.damp(u.uHover.value, isHovered ? 1 : 0, 8, delta);660 u.uHover.value = lift;661662 // Hover: the card lifts out of the wall and straightens up to face the camera663 mesh.position.set(x, y, lift * hoverElevation);664 mesh.rotation.x = lift * tilt;665 mesh.scale.setScalar(1 + lift * 0.08);666667 // Parallax: the image slides inside its card as the card travels across the wall668 u.uOffset.value.set((-x / spanW) * PARALLAX, (-y / spanH) * PARALLAX);669 // Fade near the wrap edges so recycling is never visible670 const edge = Math.max(Math.abs(x) / spanW, Math.abs(y) / spanH);671 u.uOpacity.value = 1 - THREE.MathUtils.smoothstep(edge, 0.34, 0.5);672 u.uDim.value = THREE.MathUtils.smoothstep(edge, 0.15, 0.45) * 0.5;673 });674675 const url = images[cellImage(cell[0], cell[1], images.length)];676677 return (678 <ImageCard679 ref={meshRef}680 url={url}681 width={CARD_WIDTH}682 height={CARD_HEIGHT}683 geometry={geometry}684 zoom={1.25}685 radius={0.1}686 onTexture={onTexture}687 onPointerOver={(e: ThreeEvent<PointerEvent>) => {688 e.stopPropagation();689 hovered.current = id;690 }}691 onPointerOut={() => {692 if (hovered.current === id) hovered.current = "";693 }}694 />695 );696});697698const Wall = memo(function Wall({ images, gridSize, tiltAngle, gap, hoverElevation }: Required<Omit<PerspectiveGridProps, "pauseWhenOffscreen" | "lowPowerMode">>) {699 const onTexture = useGalleryTextures(images);700 const size = useThree((state) => state.size);701 const camera = useThree((state) => state.camera);702 const pan = useRef<Pan>({ x: 0, y: 0, tx: 0, ty: 0, vx: 0, vy: 0 });703 const hovered = useRef("");704 const [cols, rows] = [Math.max(2, Math.round(gridSize[0])), Math.max(2, Math.round(gridSize[1]))];705 const cellW = CARD_WIDTH + gap;706 const cellH = CARD_HEIGHT + gap;707 const tilt = THREE.MathUtils.degToRad(tiltAngle);708709 const geometry = useMemo(() => createCardGeometry(CARD_WIDTH, CARD_HEIGHT), []);710 useEffect(() => () => geometry.dispose(), [geometry]);711712 // Slots swap images as they wrap: preload every image so a swap never shows a placeholder713 const imagesKey = images.join("\n");714 useEffect(() => {715 if (imagesKey) useTexture.preload(imagesKey.split("\n"));716 }, [imagesKey]);717718 // Pixels → world units on the wall (at the camera's distance to it)719 const worldPerPixel = () => {720 const distance = camera.position.length();721 const perspective = camera as THREE.PerspectiveCamera;722 const visibleHeight = 2 * distance * Math.tan(THREE.MathUtils.degToRad(perspective.fov / 2));723 return visibleHeight / size.height;724 };725726 useCanvasDrag({727 onStart: () => {728 pan.current.vx = 0;729 pan.current.vy = 0;730 },731 onMove: (dx, dy) => {732 const k = worldPerPixel();733 pan.current.tx += dx * k;734 pan.current.ty -= (dy * k) / Math.cos(tilt); // the tilt foreshortens vertical motion735 },736 onEnd: (vx, vy) => {737 const k = worldPerPixel();738 pan.current.vx = vx * k;739 pan.current.vy = (-vy * k) / Math.cos(tilt);740 },741 });742743 useFrame((state, delta) => {744 const dt = Math.min(delta, 1 / 30);745 const p = pan.current;746 // Throw inertia, then ease the wall towards its target747 p.tx += p.vx * dt;748 p.ty += p.vy * dt;749 p.vx *= Math.exp(-3.5 * dt);750 p.vy *= Math.exp(-3.5 * dt);751 p.x = THREE.MathUtils.damp(p.x, p.tx, 8, dt);752 p.y = THREE.MathUtils.damp(p.y, p.ty, 8, dt);753754 // The camera leans towards the pointer: the whole wall shifts in perspective755 state.camera.position.x = THREE.MathUtils.damp(state.camera.position.x, state.pointer.x * 0.8, 2.5, dt);756 state.camera.position.y = THREE.MathUtils.damp(state.camera.position.y, state.pointer.y * 0.5, 2.5, dt);757 state.camera.lookAt(0, 0, 0);758 });759760 const slots = useMemo(() => {761 const list: [number, number][] = [];762 for (let row = 0; row < rows; row++) for (let col = 0; col < cols; col++) list.push([col, row]);763 return list;764 }, [cols, rows]);765766 if (!images.length) return null;767768 return (769 <group rotation={[-tilt, 0, 0]}>770 {slots.map(([col, row]) => (771 <Slot772 key={`${col}:${row}`}773 col={col}774 row={row}775 cols={cols}776 rows={rows}777 cellW={cellW}778 cellH={cellH}779 images={images}780 pan={pan}781 hovered={hovered}782 geometry={geometry}783 tilt={tilt}784 hoverElevation={hoverElevation}785 onTexture={onTexture}786 />787 ))}788 </group>789 );790});791792const DEFAULT_GRID: [number, number] = [9, 9];793794function InfinitePerspectiveGrid({ images, gridSize = DEFAULT_GRID, tiltAngle = 32, gap = 0.25, hoverElevation = 0.6, pauseWhenOffscreen, lowPowerMode }: PerspectiveGridProps) {795 return (796 <GalleryCanvas pauseWhenOffscreen={pauseWhenOffscreen} lowPowerMode={lowPowerMode} touchAction="none" camera={{ position: [0, 0, 10], fov: 45 }}>797 <Wall images={images} gridSize={gridSize} tiltAngle={tiltAngle} gap={gap} hoverElevation={hoverElevation} />798 </GalleryCanvas>799 );800}801802export default memo(InfinitePerspectiveGrid);
03
Drop it in a page
Updated live with the settings above.
app/page.tsx
1import InfinitePerspectiveGrid from "@/components/InfinitePerspectiveGrid";23export default function Section() {4 return (5 // The component fills this box: give it a position and a height6 <div style={{ position: "relative", width: "100%", height: "100vh" }}>7 <InfinitePerspectiveGrid8 images={[9 "/3d1.jpg",10 "/3d2.jpg",11 "/3d3.jpg",12 "/3d4.jpg",13 "/blackhole.jpg",14 "/cowboy.jpg",15 "/girl.jpg",16 "/haine.jpg",17 "/heart.jpg",18 "/piastri.jpg",19 "/touching.jpg",20 "/scroll-expand-bg.jpg",21 ]}22 tiltAngle={32}23 gap={0.25}24 hoverElevation={0.6}25 />26 </div>27 );28}