Loading…
← All components

Gallery · Tunnel

Depth Tunnel

Images lining a tunnel you fly through with the wheel, handing the scroll back to the page at either end.

<DepthTunnelGallery />Live

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 depth-tunnel
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/DepthTunnelGallery.tsx and paste it in.

components/DepthTunnelGallery.tsx
1"use client";
2
3import {
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} from "react";
17import * as THREE from "three";
18import {
19 Canvas,
20 useFrame,
21 useThree,
22 type CanvasProps,
23 type ThreeElements,
24 type ThreeEvent,
25} from "@react-three/fiber";
26import { useTexture } from "@react-three/drei";
27
28/**
29 * The shared props API of DeepUI's individual 3D components (not the full-page templates, which keep
30 * their own tailored scenes).
31 *
32 * The props are grouped by concern. A component extends ONLY the groups it really applies, so its
33 * type never advertises a knob that does nothing (a card has no particles, a background has no tilt):
34 *
35 * interface MyCardProps extends CursorProps, TiltProps, MaterialProps, PerformanceProps { … }
36 *
37 * `Base3DComponentProps` is every group at once, for tooling that handles any component. Same name,
38 * same unit and same meaning everywhere; the default values live in DEFAULT_3D_PROPS. These files are
39 * inlined into each component's single-file bundle (lib/bundle-source.mjs), only what it uses.
40 */
41
42/** Which rotation axes follow the pointer. "x-only": the object nods (up / down); "y-only": it turns (left / right). */
43export type TiltAxis = "both" | "x-only" | "y-only" | "none";
44
45/** 1. Cursor: how the pointer pulls, pushes and drags the object. */
46interface CursorProps {
47 /** 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). */
48 cursorRadius?: number;
49 /** Positive pulls things towards the pointer, negative pushes them away (repulsion, shockwave). Default 1. */
50 cursorForce?: number;
51 /** How far the object slides towards the pointer, 0 (stays put) to 1 (follows closely). Default 0. */
52 magneticStrength?: number;
53 /** Share of the remaining distance the motion closes each frame (at 60 fps), 0.01 (heavy, slow) to 1 (instant). Default 0.1. */
54 cursorDamping?: number;
55}
56
57/** 2. Tilt and parallax: the object leans towards the pointer, its layers slide against each other. */
58interface TiltProps {
59 /** Largest lean towards the pointer, in degrees. Default 15. */
60 maxTiltAngle?: number;
61 /** Axes that follow the pointer. Default "both". */
62 tiltAxis?: TiltAxis;
63 /** Lean away from the pointer instead of towards it. Default false. */
64 invertTilt?: boolean;
65 /** How far apart the depth layers slide when the object tilts, 0 (flat) to 2. Default 1. */
66 parallaxOffset?: number;
67}
68
69/** 3. Text and 3D typography, for components that draw a label. */
70interface Text3DProps {
71 /** The label drawn by the component. */
72 text?: string;
73 /** Scale of the lettering. Default 1. */
74 fontSize?: number;
75 /** Extrusion depth of 3D letters. Default 0.2. */
76 textDepth?: number;
77 /** Bevelled, light-catching edges on 3D letters. Default true. */
78 bevelEnabled?: boolean;
79 /** Custom font: a .woff / .ttf (flat text) or a typeface .json (extruded text). */
80 fontUrl?: string;
81}
82
83/** 4. Rendering, materials and glow. */
84interface MaterialProps {
85 /** Main color of the object. Default "#6366f1". */
86 primaryColor?: string;
87 /** Color of the glow. Default "#00f0ff". */
88 emissiveColor?: string;
89 /** Strength of the glow, 0 (none) to 3. Default 1. */
90 emissiveIntensity?: number;
91 /** 0 (mirror, glass) to 1 (matte). Default 0.3. */
92 roughness?: number;
93 /** 0 (plastic, organic) to 1 (metal). Default 0.5. */
94 metalness?: number;
95 /** 0 (opaque) to 1 (clear glass): see-through, refracting surfaces. Default 0. */
96 transmission?: number;
97 /** Technical wireframe rendering. Default false. */
98 wireframe?: boolean;
99}
100
101/** 5. Particles, idle motion and shader animation. */
102interface MotionProps {
103 /** Number of instanced elements. Default depends on the component. */
104 particleCount?: number;
105 /** Spin on its own, in radians per second (negative: the other way; 0.5 ≈ one turn in 12 s). Default 0. */
106 autoRotateSpeed?: number;
107 /** Pulses or ripples per second. Default 1. */
108 pulseRate?: number;
109 /** Amplitude of the noise deformation, 0 (none) to 2. Default 1. */
110 displacementScale?: number;
111}
112
113/** 6. Environment and camera. */
114interface EnvironmentProps {
115 /** Camera field of view, in degrees. Default depends on the component. */
116 cameraFov?: number;
117 /** Color of the depth fog. Default "#0a0a0a". */
118 fogColor?: string;
119 /** Thickness of the fog, 0 (none) to 0.2. Default 0. */
120 fogDensity?: number;
121}
122
123/** 7. Performance and accessibility. */
124interface PerformanceProps {
125 /** Lighter rendering for weak devices: pixel ratio 1, fewer instances, smaller environment maps. Default false. */
126 lowPowerMode?: boolean;
127 /** Under the OS "reduce motion" setting, stop idle spin, pulses and deformation (pointer feedback stays). Default true. */
128 respectReducedMotion?: boolean;
129 /** Stop the render loop while the component is scrolled out of view. Default true. */
130 pauseWhenOffscreen?: boolean;
131}
132
133/** Every group at once. Components extend only the groups they apply (see the top of this file). */
134interface Base3DComponentProps
135 extends CursorProps,
136 TiltProps,
137 Text3DProps,
138 MaterialProps,
139 MotionProps,
140 EnvironmentProps,
141 PerformanceProps {}
142
143type Defaults = Required<Omit<Base3DComponentProps, "text" | "fontUrl" | "particleCount" | "cameraFov">>;
144
145/** The values a prop takes when it is left out. A component may override one, and then documents it. */
146const DEFAULT_3D_PROPS: Defaults = {
147 cursorRadius: 220,
148 cursorForce: 1,
149 magneticStrength: 0,
150 cursorDamping: 0.1,
151 maxTiltAngle: 15,
152 tiltAxis: "both",
153 invertTilt: false,
154 parallaxOffset: 1,
155 fontSize: 1,
156 textDepth: 0.2,
157 bevelEnabled: true,
158 primaryColor: "#6366f1",
159 emissiveColor: "#00f0ff",
160 emissiveIntensity: 1,
161 roughness: 0.3,
162 metalness: 0.5,
163 transmission: 0,
164 wireframe: false,
165 autoRotateSpeed: 0,
166 pulseRate: 1,
167 displacementScale: 1,
168 fogColor: "#0a0a0a",
169 fogDensity: 0,
170 lowPowerMode: false,
171 respectReducedMotion: true,
172 pauseWhenOffscreen: true,
173};
174
175/** Fills the positioned parent. Unlike the backgrounds, galleries receive pointer events. */
176const GALLERY_STYLE: CSSProperties = {
177 position: "absolute",
178 top: 0,
179 left: 0,
180 width: "100%",
181 height: "100%",
182};
183
184interface GalleryCanvasProps extends Omit<CanvasProps, "children" | "style" | "frameloop" | "gl">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {
185 children: ReactNode;
186 /**
187 * The gallery uses the wheel: Lenis (site-wide smooth scroll) is told to leave wheel events
188 * over the canvas alone, so the gallery's own handler decides whether the page scrolls.
189 */
190 captureWheel?: boolean;
191 /** CSS touch-action of the canvas: "pan-y" keeps vertical page scrolling on touch screens. */
192 touchAction?: CSSProperties["touchAction"];
193}
194
195/**
196 * Ready-to-use <Canvas> shared by every gallery: the render loop pauses while the gallery is
197 * scrolled out of view, and R3F disposes the renderer and its WebGL context on unmount.
198 */
199function GalleryCanvas({ children, captureWheel = false, touchAction = "pan-y", dpr = [1, 2], pauseWhenOffscreen = DEFAULT_3D_PROPS.pauseWhenOffscreen, lowPowerMode = DEFAULT_3D_PROPS.lowPowerMode, ...canvasProps }: GalleryCanvasProps) {
200 const containerRef = useRef<HTMLDivElement>(null);
201 const [inView, setInView] = useState(true);
202
203 useEffect(() => {
204 const el = containerRef.current;
205 if (!el) return undefined;
206 const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting));
207 observer.observe(el);
208 return () => observer.disconnect();
209 }, []);
210
211 return (
212 <div ref={containerRef} style={GALLERY_STYLE} {...(captureWheel ? { "data-lenis-prevent": "" } : {})}>
213 <Canvas
214 dpr={lowPowerMode ? 1 : dpr}
215 frameloop={inView || !pauseWhenOffscreen ? "always" : "never"}
216 gl={{ antialias: true, alpha: true, powerPreference: "high-performance" }}
217 style={{ touchAction }}
218 {...canvasProps}
219 >
220 {children}
221 </Canvas>
222 </div>
223 );
224}
225
226interface DragHandlers {
227 /** false: the canvas ignores drags (no grab cursor). Default true. */
228 enabled?: boolean;
229 onStart?: () => void;
230 /** Movement since the previous event, in CSS pixels. */
231 onMove: (dx: number, dy: number) => void;
232 /** Release velocity, in CSS pixels per second (for inertia). */
233 onEnd?: (vx: number, vy: number) => void;
234}
235
236/** Drag on the canvas (mouse, pen or touch), with release velocity for inertia. */
237function useCanvasDrag(handlers: DragHandlers) {
238 const gl = useThree((state) => state.gl);
239 const handlersRef = useRef(handlers);
240 useEffect(() => {
241 handlersRef.current = handlers;
242 });
243
244 useEffect(() => {
245 const el = gl.domElement;
246 let pointerId: number | null = null;
247 let lastX = 0;
248 let lastY = 0;
249 let lastTime = 0;
250 let vx = 0;
251 let vy = 0;
252 const grab = () => (handlersRef.current.enabled === false ? "" : "grab");
253 el.style.cursor = grab();
254
255 const down = (event: PointerEvent) => {
256 if (event.button !== 0 || pointerId !== null || handlersRef.current.enabled === false) return;
257 pointerId = event.pointerId;
258 lastX = event.clientX;
259 lastY = event.clientY;
260 lastTime = performance.now();
261 vx = 0;
262 vy = 0;
263 el.style.cursor = "grabbing";
264 handlersRef.current.onStart?.();
265 };
266 const move = (event: PointerEvent) => {
267 if (event.pointerId !== pointerId) return;
268 const now = performance.now();
269 const dt = Math.max(1, now - lastTime) / 1000;
270 const dx = event.clientX - lastX;
271 const dy = event.clientY - lastY;
272 // Smoothed velocity: a single jittery event at release must not decide the inertia
273 vx = vx * 0.6 + (dx / dt) * 0.4;
274 vy = vy * 0.6 + (dy / dt) * 0.4;
275 lastX = event.clientX;
276 lastY = event.clientY;
277 lastTime = now;
278 handlersRef.current.onMove(dx, dy);
279 };
280 const up = (event: PointerEvent) => {
281 if (event.pointerId !== pointerId) return;
282 pointerId = null;
283 el.style.cursor = grab();
284 // A pause before releasing means no throw
285 const idle = performance.now() - lastTime > 80;
286 handlersRef.current.onEnd?.(idle ? 0 : vx, idle ? 0 : vy);
287 };
288
289 el.addEventListener("pointerdown", down);
290 window.addEventListener("pointermove", move, { passive: true });
291 window.addEventListener("pointerup", up);
292 window.addEventListener("pointercancel", up);
293 return () => {
294 el.removeEventListener("pointerdown", down);
295 window.removeEventListener("pointermove", move);
296 window.removeEventListener("pointerup", up);
297 window.removeEventListener("pointercancel", up);
298 el.style.cursor = "";
299 };
300 }, [gl]);
301}
302
303/**
304 * Wheel over the canvas. The handler returns true when it used the event: the page then does not
305 * scroll. Returning false (e.g. at the end of a tunnel) lets the page scroll on.
306 */
307function useCanvasWheel(onWheel: (event: WheelEvent) => boolean) {
308 const gl = useThree((state) => state.gl);
309 const handlerRef = useRef(onWheel);
310 useEffect(() => {
311 handlerRef.current = onWheel;
312 });
313 useEffect(() => {
314 const el = gl.domElement;
315 const listener = (event: WheelEvent) => {
316 if (handlerRef.current(event)) event.preventDefault();
317 };
318 el.addEventListener("wheel", listener, { passive: false });
319 return () => el.removeEventListener("wheel", listener);
320 }, [gl]);
321}
322
323/**
324 * Collects the textures loaded by a gallery's cards and disposes them (plus drei's loader cache
325 * entries) when the gallery unmounts or its image list changes.
326 */
327function useGalleryTextures(urls: string[]) {
328 const textures = useRef(new Set<THREE.Texture>());
329 const key = urls.join("\n");
330 const onTexture = useCallback((texture: THREE.Texture) => {
331 textures.current.add(texture);
332 }, []);
333
334 useEffect(() => {
335 const loaded = textures.current;
336 return () => {
337 loaded.forEach((texture) => texture.dispose());
338 loaded.clear();
339 const list = key ? key.split("\n") : [];
340 if (list.length) useTexture.clear(list);
341 };
342 }, [key]);
343
344 return onTexture;
345}
346
347/** Repeats the image list until it has at least `min` entries (a sphere or a ring needs enough cards). */
348function cycleImages(images: string[], min: number) {
349 if (!images.length) return [];
350 const count = Math.max(images.length, min);
351 return Array.from({ length: count }, (_, i) => images[i % images.length]);
352}
353
354const cardVertexShader = /* glsl */ `
355uniform float uCurve; // 1 / radius: bends the card around the Y axis, convex side out (0 = flat)
356
357varying vec2 vUv;
358varying float vFacing;
359
360void main() {
361 vUv = uv;
362 vec3 p = position;
363 vec3 n = vec3(0.0, 0.0, 1.0);
364 if (uCurve > 0.0001) {
365 float a = p.x * uCurve;
366 p.x = sin(a) / uCurve;
367 p.z = (cos(a) - 1.0) / uCurve;
368 n = vec3(sin(a), 0.0, cos(a));
369 }
370 vec4 mvPosition = modelViewMatrix * vec4(p, 1.0);
371 vFacing = abs(dot(normalize(normalMatrix * n), normalize(-mvPosition.xyz)));
372 gl_Position = projectionMatrix * mvPosition;
373}
374`;
375
376const cardFragmentShader = /* glsl */ `
377uniform sampler2D uMap;
378uniform float uHasMap; // 1 once the texture is loaded
379uniform float uReveal; // 0 → 1 fade from the placeholder to the image
380uniform float uImageAspect;
381uniform vec2 uSize; // card size in world units
382uniform float uRadius; // corner radius in world units
383uniform float uZoom; // > 1 crops into the image (headroom for parallax)
384uniform vec2 uOffset; // image shift inside the card (parallax), in UV units
385uniform float uBlur; // motion blur length, in UV units
386uniform vec2 uBlurDir;
387uniform float uOpacity;
388uniform float uDim; // 0 = full brightness, 1 = black
389uniform float uHover; // 0 → 1 highlight
390uniform float uShade; // how much faces turned away from the camera darken
391uniform float uTime;
392uniform vec3 uTint; // placeholder color
393
394varying vec2 vUv;
395varying float vFacing;
396
397// "object-fit: cover": the image fills the card without stretching
398vec2 coverUv(vec2 uv) {
399 float planeAspect = uSize.x / uSize.y;
400 vec2 scale = planeAspect > uImageAspect ? vec2(1.0, uImageAspect / planeAspect) : vec2(planeAspect / uImageAspect, 1.0);
401 return (uv - 0.5) * scale / uZoom + 0.5 + uOffset;
402}
403
404float roundedMask(vec2 uv) {
405 vec2 p = (uv - 0.5) * uSize;
406 vec2 q = abs(p) - (uSize * 0.5 - uRadius);
407 float d = length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - uRadius;
408 float aa = fwidth(d);
409 return 1.0 - smoothstep(-aa, aa, d);
410}
411
412void main() {
413 vec2 uv = vUv;
414 // Seen from behind (a ring's far side), the image would be mirrored: flip it back
415 if (!gl_FrontFacing) uv.x = 1.0 - uv.x;
416
417 float mask = roundedMask(vUv);
418 float alpha = mask * uOpacity;
419 if (alpha < 0.005) discard;
420
421 // Placeholder: dark tint with a sweeping shimmer while the texture loads
422 float shimmer = pow(max(0.0, sin((vUv.x - vUv.y * 0.5) * 3.0 - uTime * 2.5)), 12.0);
423 vec3 color = uTint + shimmer * 0.06;
424
425 if (uHasMap > 0.5) {
426 vec2 imageUv = coverUv(uv);
427 vec3 image;
428 if (uBlur > 0.0005) {
429 // Motion blur: 7 taps along the direction of travel
430 image = vec3(0.0);
431 for (int i = 0; i < 7; i++) {
432 float t = (float(i) / 6.0 - 0.5) * uBlur;
433 image += texture2D(uMap, imageUv + uBlurDir * t).rgb;
434 }
435 image /= 7.0;
436 } else {
437 image = texture2D(uMap, imageUv).rgb;
438 }
439 color = mix(color, image, uReveal);
440 }
441
442 color *= mix(1.0, 0.35 + 0.65 * vFacing, uShade);
443 color *= 1.0 - uDim;
444 color += uHover * 0.07;
445 gl_FragColor = vec4(color, alpha);
446 #include <colorspace_fragment>
447}
448`;
449
450interface CardUniforms {
451 uMap: THREE.IUniform<THREE.Texture | null>;
452 uHasMap: THREE.IUniform<number>;
453 uReveal: THREE.IUniform<number>;
454 uImageAspect: THREE.IUniform<number>;
455 uSize: THREE.IUniform<THREE.Vector2>;
456 uRadius: THREE.IUniform<number>;
457 uCurve: THREE.IUniform<number>;
458 uZoom: THREE.IUniform<number>;
459 uOffset: THREE.IUniform<THREE.Vector2>;
460 uBlur: THREE.IUniform<number>;
461 uBlurDir: THREE.IUniform<THREE.Vector2>;
462 uOpacity: THREE.IUniform<number>;
463 uDim: THREE.IUniform<number>;
464 uHover: THREE.IUniform<number>;
465 uShade: THREE.IUniform<number>;
466 uTime: THREE.IUniform<number>;
467 uTint: THREE.IUniform<THREE.Color>;
468}
469
470function createCardMaterial() {
471 const uniforms: CardUniforms = {
472 uMap: { value: null },
473 uHasMap: { value: 0 },
474 uReveal: { value: 0 },
475 uImageAspect: { value: 1 },
476 uSize: { value: new THREE.Vector2(1, 1) },
477 uRadius: { value: 0.06 },
478 uCurve: { value: 0 },
479 uZoom: { value: 1 },
480 uOffset: { value: new THREE.Vector2() },
481 uBlur: { value: 0 },
482 uBlurDir: { value: new THREE.Vector2(0, 1) },
483 uOpacity: { value: 1 },
484 uDim: { value: 0 },
485 uHover: { value: 0 },
486 uShade: { value: 0 },
487 uTime: { value: 0 },
488 uTint: { value: new THREE.Color() },
489 };
490 return new THREE.ShaderMaterial({
491 uniforms: uniforms as unknown as Record<string, THREE.IUniform>,
492 vertexShader: cardVertexShader,
493 fragmentShader: cardFragmentShader,
494 transparent: true,
495 side: THREE.DoubleSide,
496 });
497}
498
499/** Typed access to a card's uniforms from its mesh (galleries animate them in useFrame). */
500function cardUniforms(mesh: THREE.Mesh) {
501 return (mesh.material as THREE.ShaderMaterial).uniforms as unknown as CardUniforms;
502}
503
504/** Plane sized in world units; enough columns to bend smoothly when the card is curved. */
505function createCardGeometry(width: number, height: number, segments = 1) {
506 return new THREE.PlaneGeometry(width, height, segments, 1);
507}
508
509function TextureBinder({ url, material, onTexture }: { url: string; material: THREE.ShaderMaterial; onTexture?: (texture: THREE.Texture) => void }) {
510 const texture = useTexture(url); // suspends until loaded; drei caches it per URL
511 useLayoutEffect(() => {
512 if (texture.colorSpace !== THREE.SRGBColorSpace) {
513 texture.colorSpace = THREE.SRGBColorSpace;
514 texture.needsUpdate = true;
515 }
516 texture.anisotropy = 4;
517 const image = texture.image as { width?: number; height?: number } | undefined;
518 const u = material.uniforms as unknown as CardUniforms;
519 if (u.uMap.value !== texture) u.uReveal.value = 0; // fade in each new image
520 u.uMap.value = texture;
521 u.uImageAspect.value = image?.width && image?.height ? image.width / image.height : 1;
522 u.uHasMap.value = 1;
523 onTexture?.(texture);
524 }, [texture, material, onTexture]);
525 return null;
526}
527
528/** A failed image keeps its placeholder instead of breaking the whole gallery. */
529class TextureErrorBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {
530 state = { failed: false };
531 static getDerivedStateFromError() {
532 return { failed: true };
533 }
534 render() {
535 return this.state.failed ? null : this.props.children;
536 }
537}
538
539interface ImageCardProps extends Omit<ThreeElements["mesh"], "geometry" | "material" | "ref"> {
540 url: string;
541 width: number;
542 height: number;
543 /** Shared plane from createCardGeometry(width, height, segments). */
544 geometry: THREE.BufferGeometry;
545 radius?: number;
546 /** 1 / radius of the surface the card is bent on (0 = flat). */
547 curve?: number;
548 /** 0–1: darken the card as it turns away from the camera. */
549 shade?: number;
550 zoom?: number;
551 placeholderColor?: string;
552 onTexture?: (texture: THREE.Texture) => void;
553 ref?: Ref<THREE.Mesh>;
554}
555
556/**
557 * Image card: rounded corners, cover-fit image, placeholder shimmer while loading, fade-in once
558 * loaded, placeholder kept if the image fails. Its material is created once and disposed on unmount.
559 */
560const ImageCard = memo(function ImageCard({
561 url,
562 width,
563 height,
564 geometry,
565 radius = 0.06,
566 curve = 0,
567 shade = 0,
568 zoom = 1,
569 placeholderColor = "#151517",
570 onTexture,
571 ref,
572 ...meshProps
573}: ImageCardProps) {
574 const material = useMemo(() => createCardMaterial(), []);
575 const u = material.uniforms as unknown as CardUniforms;
576
577 useEffect(() => {
578 u.uSize.value.set(width, height);
579 u.uRadius.value = Math.min(radius, width / 2, height / 2);
580 u.uCurve.value = curve;
581 u.uShade.value = shade;
582 u.uZoom.value = zoom;
583 u.uTint.value.set(placeholderColor);
584 }, [u, width, height, radius, curve, shade, zoom, placeholderColor]);
585
586 useEffect(() => () => material.dispose(), [material]);
587
588 useFrame((state, delta) => {
589 if (u.uHasMap.value > 0.5) {
590 if (u.uReveal.value < 0.999) u.uReveal.value = THREE.MathUtils.damp(u.uReveal.value, 1, 5, delta);
591 } else {
592 u.uTime.value = state.clock.elapsedTime;
593 }
594 });
595
596 return (
597 // The shader bends the card: the plane's own bounds are not reliable for frustum culling
598 <mesh ref={ref} geometry={geometry} material={material} frustumCulled={false} {...meshProps}>
599 <TextureErrorBoundary key={url}>
600 <Suspense fallback={null}>
601 <TextureBinder url={url} material={material} onTexture={onTexture} />
602 </Suspense>
603 </TextureErrorBoundary>
604 </mesh>
605 );
606});
607
608export interface DepthTunnelProps extends Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {
609 images: string[];
610 /** Distance between two consecutive images along Z. Default 2.6. */
611 depthSpacing?: number;
612 /** Wheel/drag sensitivity multiplier. Default 1. */
613 scrollSpeed?: number;
614 /** Distance of the images from the tunnel axis. Default 2.4. */
615 tunnelRadius?: number;
616 /** The image list is repeated until the tunnel holds at least this many. Default 12. */
617 minCards?: number;
618 /**
619 * Scroll-linked mode: the flight follows `progressRef.current` (0 = entrance, 1 = last image), which
620 * you update yourself, e.g. from a GSAP ScrollTrigger on a pinned section. Wheel, drag and click are
621 * then left to the page.
622 */
623 progressRef?: { current: number };
624}
625
626const CARD_WIDTH = 2.2;
627const CARD_HEIGHT = 1.45;
628const GOLDEN_ANGLE = Math.PI * (3 - Math.sqrt(5));
629const CAMERA_START = 6;
630const BASE_FOV = 55;
631
632type TunnelProps = Required<Omit<DepthTunnelProps, "pauseWhenOffscreen" | "lowPowerMode" | "progressRef">> & Pick<DepthTunnelProps, "progressRef">;
633
634const Tunnel = memo(function Tunnel({ images, depthSpacing, scrollSpeed, tunnelRadius, minCards, progressRef }: TunnelProps) {
635 const onTexture = useGalleryTextures(images);
636 const cards = useMemo(() => cycleImages(images, minCards), [images, minCards]);
637 const cardRefs = useRef<(THREE.Mesh | null)[]>([]);
638 const hovered = useRef(-1);
639 const travel = useRef({ current: 0, target: 0, previous: 0 });
640 const maxTravel = (cards.length - 1) * depthSpacing;
641
642 const geometry = useMemo(() => createCardGeometry(CARD_WIDTH, CARD_HEIGHT), []);
643 useEffect(() => () => geometry.dispose(), [geometry]);
644
645 // Each image sits on the golden-angle spiral: no two neighbors line up
646 const layout = useMemo(
647 () =>
648 cards.map((_, i) => {
649 const angle = i * GOLDEN_ANGLE + 0.6;
650 return { angle, z: -i * depthSpacing, dir: new THREE.Vector2(Math.cos(angle), Math.sin(angle)) };
651 }),
652 [cards, depthSpacing]
653 );
654
655 // The wheel moves through the tunnel; at either end it hands the scroll back to the page
656 useCanvasWheel((event) => {
657 if (progressRef) return false;
658 const t = travel.current;
659 const delta = event.deltaY * 0.012 * scrollSpeed;
660 if ((t.target <= 0 && delta < 0) || (t.target >= maxTravel && delta > 0)) return false;
661 t.target = THREE.MathUtils.clamp(t.target + delta, 0, maxTravel);
662 return true;
663 });
664 useCanvasDrag({
665 enabled: !progressRef,
666 onMove: (_, dy) => {
667 const t = travel.current;
668 t.target = THREE.MathUtils.clamp(t.target - dy * 0.02 * scrollSpeed, 0, maxTravel);
669 },
670 });
671
672 useFrame((state, delta) => {
673 const dt = Math.min(delta, 1 / 30);
674 const t = travel.current;
675 if (progressRef) t.target = THREE.MathUtils.clamp(progressRef.current, 0, 1) * maxTravel;
676 t.previous = t.current;
677 t.current = THREE.MathUtils.damp(t.current, t.target, 4, dt);
678 const speed = Math.abs(t.current - t.previous) / Math.max(dt, 1e-4);
679
680 // Camera flies forward, sways with the pointer; the field of view stretches with speed
681 const camera = state.camera as THREE.PerspectiveCamera;
682 const cameraZ = CAMERA_START - t.current;
683 camera.position.set(
684 THREE.MathUtils.damp(camera.position.x, state.pointer.x * 0.5, 3, dt),
685 THREE.MathUtils.damp(camera.position.y, state.pointer.y * 0.3, 3, dt),
686 cameraZ
687 );
688 camera.lookAt(camera.position.x * 0.5, camera.position.y * 0.5, cameraZ - 10);
689 const fov = BASE_FOV + Math.min(speed, 30) * 0.5;
690 if (Math.abs(camera.fov - fov) > 0.01) {
691 camera.fov = THREE.MathUtils.damp(camera.fov, fov, 6, dt);
692 camera.updateProjectionMatrix();
693 }
694
695 const blur = Math.min(speed * 0.0035, 0.08);
696 cardRefs.current.forEach((mesh, i) => {
697 if (!mesh) return;
698 const { angle, z, dir } = layout[i];
699 const distance = cameraZ - z; // > 0 while the image is ahead
700
701 // As the camera arrives, the image glides aside so the visitor passes through
702 const approach = 1 - THREE.MathUtils.smoothstep(distance, 0, depthSpacing * 2.2);
703 const r = tunnelRadius * (1 + approach * 1.1);
704 mesh.position.set(Math.cos(angle) * r, Math.sin(angle) * r * 0.62, z);
705 mesh.rotation.set(Math.sin(angle) * 0.18 * (1 + approach), -Math.cos(angle) * 0.22 * (1 + approach), 0);
706
707 const u = cardUniforms(mesh);
708 // Far images emerge from the dark; images behind the camera fade out
709 const fadeIn = 1 - THREE.MathUtils.smoothstep(distance, depthSpacing * 5, depthSpacing * 9);
710 const fadeOut = THREE.MathUtils.smoothstep(distance, 0.2, 1.4);
711 u.uOpacity.value = fadeIn * fadeOut;
712 u.uDim.value = THREE.MathUtils.smoothstep(distance, depthSpacing * 1.5, depthSpacing * 8) * 0.7;
713 // Motion blur along the image's radial direction on screen
714 u.uBlur.value = blur;
715 u.uBlurDir.value.copy(dir);
716 const hover = THREE.MathUtils.damp(u.uHover.value, hovered.current === i ? 1 : 0, 10, dt);
717 u.uHover.value = hover;
718 mesh.scale.setScalar(1 + hover * 0.05);
719 });
720 });
721
722 return (
723 <>
724 {cards.map((url, i) => (
725 <ImageCard
726 key={i}
727 ref={(mesh) => {
728 cardRefs.current[i] = mesh;
729 }}
730 url={url}
731 width={CARD_WIDTH}
732 height={CARD_HEIGHT}
733 geometry={geometry}
734 radius={0.08}
735 onTexture={onTexture}
736 onPointerOver={(e: ThreeEvent<PointerEvent>) => {
737 e.stopPropagation();
738 hovered.current = i;
739 }}
740 onPointerOut={() => {
741 if (hovered.current === i) hovered.current = -1;
742 }}
743 onClick={(e: ThreeEvent<MouseEvent>) => {
744 e.stopPropagation();
745 // Click: fly to just in front of that image
746 if (e.delta < 6 && !progressRef) travel.current.target = THREE.MathUtils.clamp(-layout[i].z - CAMERA_START + 4.2, 0, maxTravel);
747 }}
748 />
749 ))}
750 </>
751 );
752});
753
754function DepthTunnelGallery({ images, depthSpacing = 2.6, scrollSpeed = 1, tunnelRadius = 2.4, minCards = 12, progressRef, pauseWhenOffscreen, lowPowerMode }: DepthTunnelProps) {
755 // Scroll-linked, the page keeps the wheel and vertical swipes
756 const linked = Boolean(progressRef);
757 return (
758 <GalleryCanvas
759 pauseWhenOffscreen={pauseWhenOffscreen}
760 lowPowerMode={lowPowerMode}
761 captureWheel={!linked}
762 touchAction={linked ? "pan-y" : "pan-x"}
763 camera={{ position: [0, 0, CAMERA_START], fov: BASE_FOV, near: 0.1, far: 80 }}
764 >
765 <Tunnel
766 images={images}
767 depthSpacing={depthSpacing}
768 scrollSpeed={scrollSpeed}
769 tunnelRadius={tunnelRadius}
770 minCards={minCards}
771 progressRef={progressRef}
772 />
773 </GalleryCanvas>
774 );
775}
776
777export default memo(DepthTunnelGallery);
03

Drop it in a page

Updated live with the settings above.

app/page.tsx
1import DepthTunnelGallery from "@/components/DepthTunnelGallery";
2
3export default function Section() {
4 return (
5 // The component fills this box: give it a position and a height
6 <div style={{ position: "relative", width: "100%", height: "100vh" }}>
7 <DepthTunnelGallery
8 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 depthSpacing={2.6}
23 tunnelRadius={2.4}
24 scrollSpeed={1}
25 />
26 </div>
27 );
28}
Next componentSphere Cloud→