Loading…
← All components

Gallery · Carousel

Cylinder Gallery

A ring of image cards turning on itself; drag or scroll to spin it, click a card to bring it to the front.

<CylinderGallery />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 cylinder-gallery
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/CylinderGallery.tsx and paste it in.

components/CylinderGallery.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
226function usePrefersReducedMotion() {
227 const [reduced, setReduced] = useState(false);
228 useEffect(() => {
229 const query = window.matchMedia("(prefers-reduced-motion: reduce)");
230 const sync = () => setReduced(query.matches);
231 sync();
232 query.addEventListener("change", sync);
233 return () => query.removeEventListener("change", sync);
234 }, []);
235 return reduced;
236}
237
238interface DragHandlers {
239 /** false: the canvas ignores drags (no grab cursor). Default true. */
240 enabled?: boolean;
241 onStart?: () => void;
242 /** Movement since the previous event, in CSS pixels. */
243 onMove: (dx: number, dy: number) => void;
244 /** Release velocity, in CSS pixels per second (for inertia). */
245 onEnd?: (vx: number, vy: number) => void;
246}
247
248/** Drag on the canvas (mouse, pen or touch), with release velocity for inertia. */
249function useCanvasDrag(handlers: DragHandlers) {
250 const gl = useThree((state) => state.gl);
251 const handlersRef = useRef(handlers);
252 useEffect(() => {
253 handlersRef.current = handlers;
254 });
255
256 useEffect(() => {
257 const el = gl.domElement;
258 let pointerId: number | null = null;
259 let lastX = 0;
260 let lastY = 0;
261 let lastTime = 0;
262 let vx = 0;
263 let vy = 0;
264 const grab = () => (handlersRef.current.enabled === false ? "" : "grab");
265 el.style.cursor = grab();
266
267 const down = (event: PointerEvent) => {
268 if (event.button !== 0 || pointerId !== null || handlersRef.current.enabled === false) return;
269 pointerId = event.pointerId;
270 lastX = event.clientX;
271 lastY = event.clientY;
272 lastTime = performance.now();
273 vx = 0;
274 vy = 0;
275 el.style.cursor = "grabbing";
276 handlersRef.current.onStart?.();
277 };
278 const move = (event: PointerEvent) => {
279 if (event.pointerId !== pointerId) return;
280 const now = performance.now();
281 const dt = Math.max(1, now - lastTime) / 1000;
282 const dx = event.clientX - lastX;
283 const dy = event.clientY - lastY;
284 // Smoothed velocity: a single jittery event at release must not decide the inertia
285 vx = vx * 0.6 + (dx / dt) * 0.4;
286 vy = vy * 0.6 + (dy / dt) * 0.4;
287 lastX = event.clientX;
288 lastY = event.clientY;
289 lastTime = now;
290 handlersRef.current.onMove(dx, dy);
291 };
292 const up = (event: PointerEvent) => {
293 if (event.pointerId !== pointerId) return;
294 pointerId = null;
295 el.style.cursor = grab();
296 // A pause before releasing means no throw
297 const idle = performance.now() - lastTime > 80;
298 handlersRef.current.onEnd?.(idle ? 0 : vx, idle ? 0 : vy);
299 };
300
301 el.addEventListener("pointerdown", down);
302 window.addEventListener("pointermove", move, { passive: true });
303 window.addEventListener("pointerup", up);
304 window.addEventListener("pointercancel", up);
305 return () => {
306 el.removeEventListener("pointerdown", down);
307 window.removeEventListener("pointermove", move);
308 window.removeEventListener("pointerup", up);
309 window.removeEventListener("pointercancel", up);
310 el.style.cursor = "";
311 };
312 }, [gl]);
313}
314
315/**
316 * Wheel over the canvas. The handler returns true when it used the event: the page then does not
317 * scroll. Returning false (e.g. at the end of a tunnel) lets the page scroll on.
318 */
319function useCanvasWheel(onWheel: (event: WheelEvent) => boolean) {
320 const gl = useThree((state) => state.gl);
321 const handlerRef = useRef(onWheel);
322 useEffect(() => {
323 handlerRef.current = onWheel;
324 });
325 useEffect(() => {
326 const el = gl.domElement;
327 const listener = (event: WheelEvent) => {
328 if (handlerRef.current(event)) event.preventDefault();
329 };
330 el.addEventListener("wheel", listener, { passive: false });
331 return () => el.removeEventListener("wheel", listener);
332 }, [gl]);
333}
334
335/**
336 * Collects the textures loaded by a gallery's cards and disposes them (plus drei's loader cache
337 * entries) when the gallery unmounts or its image list changes.
338 */
339function useGalleryTextures(urls: string[]) {
340 const textures = useRef(new Set<THREE.Texture>());
341 const key = urls.join("\n");
342 const onTexture = useCallback((texture: THREE.Texture) => {
343 textures.current.add(texture);
344 }, []);
345
346 useEffect(() => {
347 const loaded = textures.current;
348 return () => {
349 loaded.forEach((texture) => texture.dispose());
350 loaded.clear();
351 const list = key ? key.split("\n") : [];
352 if (list.length) useTexture.clear(list);
353 };
354 }, [key]);
355
356 return onTexture;
357}
358
359/** Repeats the image list until it has at least `min` entries (a sphere or a ring needs enough cards). */
360function cycleImages(images: string[], min: number) {
361 if (!images.length) return [];
362 const count = Math.max(images.length, min);
363 return Array.from({ length: count }, (_, i) => images[i % images.length]);
364}
365
366const cardVertexShader = /* glsl */ `
367uniform float uCurve; // 1 / radius: bends the card around the Y axis, convex side out (0 = flat)
368
369varying vec2 vUv;
370varying float vFacing;
371
372void main() {
373 vUv = uv;
374 vec3 p = position;
375 vec3 n = vec3(0.0, 0.0, 1.0);
376 if (uCurve > 0.0001) {
377 float a = p.x * uCurve;
378 p.x = sin(a) / uCurve;
379 p.z = (cos(a) - 1.0) / uCurve;
380 n = vec3(sin(a), 0.0, cos(a));
381 }
382 vec4 mvPosition = modelViewMatrix * vec4(p, 1.0);
383 vFacing = abs(dot(normalize(normalMatrix * n), normalize(-mvPosition.xyz)));
384 gl_Position = projectionMatrix * mvPosition;
385}
386`;
387
388const cardFragmentShader = /* glsl */ `
389uniform sampler2D uMap;
390uniform float uHasMap; // 1 once the texture is loaded
391uniform float uReveal; // 0 → 1 fade from the placeholder to the image
392uniform float uImageAspect;
393uniform vec2 uSize; // card size in world units
394uniform float uRadius; // corner radius in world units
395uniform float uZoom; // > 1 crops into the image (headroom for parallax)
396uniform vec2 uOffset; // image shift inside the card (parallax), in UV units
397uniform float uBlur; // motion blur length, in UV units
398uniform vec2 uBlurDir;
399uniform float uOpacity;
400uniform float uDim; // 0 = full brightness, 1 = black
401uniform float uHover; // 0 → 1 highlight
402uniform float uShade; // how much faces turned away from the camera darken
403uniform float uTime;
404uniform vec3 uTint; // placeholder color
405
406varying vec2 vUv;
407varying float vFacing;
408
409// "object-fit: cover": the image fills the card without stretching
410vec2 coverUv(vec2 uv) {
411 float planeAspect = uSize.x / uSize.y;
412 vec2 scale = planeAspect > uImageAspect ? vec2(1.0, uImageAspect / planeAspect) : vec2(planeAspect / uImageAspect, 1.0);
413 return (uv - 0.5) * scale / uZoom + 0.5 + uOffset;
414}
415
416float roundedMask(vec2 uv) {
417 vec2 p = (uv - 0.5) * uSize;
418 vec2 q = abs(p) - (uSize * 0.5 - uRadius);
419 float d = length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - uRadius;
420 float aa = fwidth(d);
421 return 1.0 - smoothstep(-aa, aa, d);
422}
423
424void main() {
425 vec2 uv = vUv;
426 // Seen from behind (a ring's far side), the image would be mirrored: flip it back
427 if (!gl_FrontFacing) uv.x = 1.0 - uv.x;
428
429 float mask = roundedMask(vUv);
430 float alpha = mask * uOpacity;
431 if (alpha < 0.005) discard;
432
433 // Placeholder: dark tint with a sweeping shimmer while the texture loads
434 float shimmer = pow(max(0.0, sin((vUv.x - vUv.y * 0.5) * 3.0 - uTime * 2.5)), 12.0);
435 vec3 color = uTint + shimmer * 0.06;
436
437 if (uHasMap > 0.5) {
438 vec2 imageUv = coverUv(uv);
439 vec3 image;
440 if (uBlur > 0.0005) {
441 // Motion blur: 7 taps along the direction of travel
442 image = vec3(0.0);
443 for (int i = 0; i < 7; i++) {
444 float t = (float(i) / 6.0 - 0.5) * uBlur;
445 image += texture2D(uMap, imageUv + uBlurDir * t).rgb;
446 }
447 image /= 7.0;
448 } else {
449 image = texture2D(uMap, imageUv).rgb;
450 }
451 color = mix(color, image, uReveal);
452 }
453
454 color *= mix(1.0, 0.35 + 0.65 * vFacing, uShade);
455 color *= 1.0 - uDim;
456 color += uHover * 0.07;
457 gl_FragColor = vec4(color, alpha);
458 #include <colorspace_fragment>
459}
460`;
461
462interface CardUniforms {
463 uMap: THREE.IUniform<THREE.Texture | null>;
464 uHasMap: THREE.IUniform<number>;
465 uReveal: THREE.IUniform<number>;
466 uImageAspect: THREE.IUniform<number>;
467 uSize: THREE.IUniform<THREE.Vector2>;
468 uRadius: THREE.IUniform<number>;
469 uCurve: THREE.IUniform<number>;
470 uZoom: THREE.IUniform<number>;
471 uOffset: THREE.IUniform<THREE.Vector2>;
472 uBlur: THREE.IUniform<number>;
473 uBlurDir: THREE.IUniform<THREE.Vector2>;
474 uOpacity: THREE.IUniform<number>;
475 uDim: THREE.IUniform<number>;
476 uHover: THREE.IUniform<number>;
477 uShade: THREE.IUniform<number>;
478 uTime: THREE.IUniform<number>;
479 uTint: THREE.IUniform<THREE.Color>;
480}
481
482function createCardMaterial() {
483 const uniforms: CardUniforms = {
484 uMap: { value: null },
485 uHasMap: { value: 0 },
486 uReveal: { value: 0 },
487 uImageAspect: { value: 1 },
488 uSize: { value: new THREE.Vector2(1, 1) },
489 uRadius: { value: 0.06 },
490 uCurve: { value: 0 },
491 uZoom: { value: 1 },
492 uOffset: { value: new THREE.Vector2() },
493 uBlur: { value: 0 },
494 uBlurDir: { value: new THREE.Vector2(0, 1) },
495 uOpacity: { value: 1 },
496 uDim: { value: 0 },
497 uHover: { value: 0 },
498 uShade: { value: 0 },
499 uTime: { value: 0 },
500 uTint: { value: new THREE.Color() },
501 };
502 return new THREE.ShaderMaterial({
503 uniforms: uniforms as unknown as Record<string, THREE.IUniform>,
504 vertexShader: cardVertexShader,
505 fragmentShader: cardFragmentShader,
506 transparent: true,
507 side: THREE.DoubleSide,
508 });
509}
510
511/** Typed access to a card's uniforms from its mesh (galleries animate them in useFrame). */
512function cardUniforms(mesh: THREE.Mesh) {
513 return (mesh.material as THREE.ShaderMaterial).uniforms as unknown as CardUniforms;
514}
515
516/** Plane sized in world units; enough columns to bend smoothly when the card is curved. */
517function createCardGeometry(width: number, height: number, segments = 1) {
518 return new THREE.PlaneGeometry(width, height, segments, 1);
519}
520
521function TextureBinder({ url, material, onTexture }: { url: string; material: THREE.ShaderMaterial; onTexture?: (texture: THREE.Texture) => void }) {
522 const texture = useTexture(url); // suspends until loaded; drei caches it per URL
523 useLayoutEffect(() => {
524 if (texture.colorSpace !== THREE.SRGBColorSpace) {
525 texture.colorSpace = THREE.SRGBColorSpace;
526 texture.needsUpdate = true;
527 }
528 texture.anisotropy = 4;
529 const image = texture.image as { width?: number; height?: number } | undefined;
530 const u = material.uniforms as unknown as CardUniforms;
531 if (u.uMap.value !== texture) u.uReveal.value = 0; // fade in each new image
532 u.uMap.value = texture;
533 u.uImageAspect.value = image?.width && image?.height ? image.width / image.height : 1;
534 u.uHasMap.value = 1;
535 onTexture?.(texture);
536 }, [texture, material, onTexture]);
537 return null;
538}
539
540/** A failed image keeps its placeholder instead of breaking the whole gallery. */
541class TextureErrorBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {
542 state = { failed: false };
543 static getDerivedStateFromError() {
544 return { failed: true };
545 }
546 render() {
547 return this.state.failed ? null : this.props.children;
548 }
549}
550
551interface ImageCardProps extends Omit<ThreeElements["mesh"], "geometry" | "material" | "ref"> {
552 url: string;
553 width: number;
554 height: number;
555 /** Shared plane from createCardGeometry(width, height, segments). */
556 geometry: THREE.BufferGeometry;
557 radius?: number;
558 /** 1 / radius of the surface the card is bent on (0 = flat). */
559 curve?: number;
560 /** 0–1: darken the card as it turns away from the camera. */
561 shade?: number;
562 zoom?: number;
563 placeholderColor?: string;
564 onTexture?: (texture: THREE.Texture) => void;
565 ref?: Ref<THREE.Mesh>;
566}
567
568/**
569 * Image card: rounded corners, cover-fit image, placeholder shimmer while loading, fade-in once
570 * loaded, placeholder kept if the image fails. Its material is created once and disposed on unmount.
571 */
572const ImageCard = memo(function ImageCard({
573 url,
574 width,
575 height,
576 geometry,
577 radius = 0.06,
578 curve = 0,
579 shade = 0,
580 zoom = 1,
581 placeholderColor = "#151517",
582 onTexture,
583 ref,
584 ...meshProps
585}: ImageCardProps) {
586 const material = useMemo(() => createCardMaterial(), []);
587 const u = material.uniforms as unknown as CardUniforms;
588
589 useEffect(() => {
590 u.uSize.value.set(width, height);
591 u.uRadius.value = Math.min(radius, width / 2, height / 2);
592 u.uCurve.value = curve;
593 u.uShade.value = shade;
594 u.uZoom.value = zoom;
595 u.uTint.value.set(placeholderColor);
596 }, [u, width, height, radius, curve, shade, zoom, placeholderColor]);
597
598 useEffect(() => () => material.dispose(), [material]);
599
600 useFrame((state, delta) => {
601 if (u.uHasMap.value > 0.5) {
602 if (u.uReveal.value < 0.999) u.uReveal.value = THREE.MathUtils.damp(u.uReveal.value, 1, 5, delta);
603 } else {
604 u.uTime.value = state.clock.elapsedTime;
605 }
606 });
607
608 return (
609 // The shader bends the card: the plane's own bounds are not reliable for frustum culling
610 <mesh ref={ref} geometry={geometry} material={material} frustumCulled={false} {...meshProps}>
611 <TextureErrorBoundary key={url}>
612 <Suspense fallback={null}>
613 <TextureBinder url={url} material={material} onTexture={onTexture} />
614 </Suspense>
615 </TextureErrorBoundary>
616 </mesh>
617 );
618});
619
620export interface CylinderGalleryProps extends Pick<MotionProps, "autoRotateSpeed">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {
621 images: string[];
622 /** Ring radius in world units. Grows automatically if the cards don't fit. Default 4.2. */
623 radius?: number;
624 cardWidth?: number;
625 cardHeight?: number;
626 /** Turns on its own while nobody interacts. Default true. */
627 autoRotate?: boolean;
628 /** Radians per second. Default 0.15. */
629 autoRotateSpeed?: number;
630}
631
632const CARD_GAP = 1.14; // card pitch on the ring, as a multiple of the card width
633const IDLE_DELAY = 2.5; // seconds after an interaction before auto-rotation resumes
634
635const Ring = memo(function Ring({ images, radius, cardWidth, cardHeight, autoRotate, autoRotateSpeed }: Required<Omit<CylinderGalleryProps, "pauseWhenOffscreen" | "lowPowerMode">>) {
636 const groupRef = useRef<THREE.Group>(null);
637 const cardRefs = useRef<(THREE.Mesh | null)[]>([]);
638 const hovered = useRef(-1);
639 const reducedMotion = usePrefersReducedMotion();
640 const onTexture = useGalleryTextures(images);
641
642 // Enough cards to close the ring; the radius grows if there are more images than fit
643 const minCards = Math.max(8, Math.floor((2 * Math.PI * radius) / (cardWidth * CARD_GAP)));
644 const cards = useMemo(() => cycleImages(images, minCards), [images, minCards]);
645 const ringRadius = Math.max(radius, (cards.length * cardWidth * CARD_GAP) / (2 * Math.PI));
646 const step = (2 * Math.PI) / Math.max(1, cards.length);
647
648 const geometry = useMemo(() => createCardGeometry(cardWidth, cardHeight, 32), [cardWidth, cardHeight]);
649 useEffect(() => () => geometry.dispose(), [geometry]);
650
651 const rotation = useRef({ current: 0, target: 0, velocity: 0, lastInteraction: -Infinity });
652
653 const touch = () => {
654 rotation.current.lastInteraction = performance.now() / 1000;
655 };
656 useCanvasDrag({
657 onStart: () => {
658 touch();
659 rotation.current.velocity = 0;
660 },
661 onMove: (dx) => {
662 touch();
663 rotation.current.target += dx * 0.005;
664 },
665 onEnd: (vx) => {
666 touch();
667 rotation.current.velocity = vx * 0.005;
668 },
669 });
670 useCanvasWheel((event) => {
671 touch();
672 rotation.current.target -= (event.deltaY + event.deltaX) * 0.0015;
673 return true;
674 });
675
676 // Click: turn the ring the short way until that card faces the camera
677 const focus = useCallback(
678 (index: number) => {
679 const r = rotation.current;
680 const goal = -index * step;
681 r.target = goal + Math.round((r.target - goal) / (2 * Math.PI)) * 2 * Math.PI;
682 r.velocity = 0;
683 touch();
684 },
685 [step]
686 );
687
688 useFrame((state, delta) => {
689 const group = groupRef.current;
690 if (!group) return;
691 const dt = Math.min(delta, 1 / 30);
692 const r = rotation.current;
693
694 // Throw inertia, then auto-rotation once idle
695 r.target += r.velocity * dt;
696 r.velocity *= Math.exp(-3 * dt);
697 if (autoRotate && !reducedMotion && performance.now() / 1000 - r.lastInteraction > IDLE_DELAY) {
698 r.target += autoRotateSpeed * dt;
699 }
700 r.current = THREE.MathUtils.damp(r.current, r.target, 6, dt);
701 group.rotation.y = r.current;
702
703 // Depth: front cards large and sharp, the back of the ring small, dark and faded
704 cardRefs.current.forEach((mesh, i) => {
705 if (!mesh) return;
706 const facing = Math.cos(i * step + r.current); // 1 = facing the camera, -1 = far side
707 const t = (facing + 1) / 2;
708 const u = cardUniforms(mesh);
709 const hover = THREE.MathUtils.damp(u.uHover.value, hovered.current === i ? 1 : 0, 10, dt);
710 u.uHover.value = hover;
711 u.uDim.value = (1 - t) * 0.72;
712 u.uOpacity.value = 0.22 + 0.78 * Math.pow(t, 1.4);
713 const scale = 0.86 + 0.2 * Math.pow(t, 3) + hover * 0.05;
714 mesh.scale.setScalar(scale);
715 });
716
717 // Slight camera drift towards the pointer
718 state.camera.position.x = THREE.MathUtils.damp(state.camera.position.x, state.pointer.x * 0.6, 2, dt);
719 state.camera.position.y = THREE.MathUtils.damp(state.camera.position.y, 1.1 + state.pointer.y * 0.4, 2, dt);
720 state.camera.lookAt(0, 0, 0);
721 });
722
723 return (
724 <group ref={groupRef}>
725 {cards.map((url, i) => {
726 const angle = i * step;
727 return (
728 <ImageCard
729 key={i}
730 ref={(mesh) => {
731 cardRefs.current[i] = mesh;
732 }}
733 url={url}
734 width={cardWidth}
735 height={cardHeight}
736 geometry={geometry}
737 curve={1 / ringRadius}
738 shade={0.6}
739 radius={0.08}
740 position={[Math.sin(angle) * ringRadius, 0, Math.cos(angle) * ringRadius]}
741 rotation={[0, angle, 0]}
742 onTexture={onTexture}
743 onPointerOver={(e: ThreeEvent<PointerEvent>) => {
744 e.stopPropagation();
745 hovered.current = i;
746 }}
747 onPointerOut={() => {
748 if (hovered.current === i) hovered.current = -1;
749 }}
750 onClick={(e: ThreeEvent<MouseEvent>) => {
751 e.stopPropagation();
752 if (e.delta < 6) focus(i); // a drag is not a click
753 }}
754 />
755 );
756 })}
757 </group>
758 );
759});
760
761function CylinderGallery({
762 images,
763 radius = 4.2,
764 cardWidth = 1.6,
765 cardHeight = 2.2,
766 autoRotate = true,
767 autoRotateSpeed = 0.15,
768 pauseWhenOffscreen,
769 lowPowerMode,
770}: CylinderGalleryProps) {
771 return (
772 <GalleryCanvas pauseWhenOffscreen={pauseWhenOffscreen} lowPowerMode={lowPowerMode} captureWheel camera={{ position: [0, 1.1, radius + 6], fov: 40 }}>
773 <Ring
774 images={images}
775 radius={radius}
776 cardWidth={cardWidth}
777 cardHeight={cardHeight}
778 autoRotate={autoRotate}
779 autoRotateSpeed={autoRotateSpeed}
780 />
781 </GalleryCanvas>
782 );
783}
784
785export default memo(CylinderGallery);
03

Drop it in a page

Updated live with the settings above.

app/page.tsx
1import CylinderGallery from "@/components/CylinderGallery";
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 <CylinderGallery
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 radius={4.2}
23 cardWidth={1.6}
24 cardHeight={2.2}
25 autoRotateSpeed={0.15}
26 />
27 </div>
28 );
29}
Next componentPerspective Grid→