← All components Next componentSpiral Helix→
Gallery · Sphere
Sphere Cloud
A sphere of image cards to orbit around; click one to fly up to it, click the background to fly back.
<SphereCloudGallery />Live
Drag to orbit · click a card
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 sphere-cloud
01
Install
The 3D packages this component is built on.
$ npm install three @react-three/fiber @react-three/drei three-stdlib && npm install -D @types/three
02
Add the component
One self-contained file: create components/SphereCloudGallery.tsx and paste it in.
components/SphereCloudGallery.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} 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 { OrbitControls, useTexture } from "@react-three/drei";27import type { OrbitControls as OrbitControlsImpl } from "three-stdlib";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}226227function usePrefersReducedMotion() {228 const [reduced, setReduced] = useState(false);229 useEffect(() => {230 const query = window.matchMedia("(prefers-reduced-motion: reduce)");231 const sync = () => setReduced(query.matches);232 sync();233 query.addEventListener("change", sync);234 return () => query.removeEventListener("change", sync);235 }, []);236 return reduced;237}238239/**240 * Collects the textures loaded by a gallery's cards and disposes them (plus drei's loader cache241 * entries) when the gallery unmounts or its image list changes.242 */243function useGalleryTextures(urls: string[]) {244 const textures = useRef(new Set<THREE.Texture>());245 const key = urls.join("\n");246 const onTexture = useCallback((texture: THREE.Texture) => {247 textures.current.add(texture);248 }, []);249250 useEffect(() => {251 const loaded = textures.current;252 return () => {253 loaded.forEach((texture) => texture.dispose());254 loaded.clear();255 const list = key ? key.split("\n") : [];256 if (list.length) useTexture.clear(list);257 };258 }, [key]);259260 return onTexture;261}262263/** Repeats the image list until it has at least `min` entries (a sphere or a ring needs enough cards). */264function cycleImages(images: string[], min: number) {265 if (!images.length) return [];266 const count = Math.max(images.length, min);267 return Array.from({ length: count }, (_, i) => images[i % images.length]);268}269270const cardVertexShader = /* glsl */ `271uniform float uCurve; // 1 / radius: bends the card around the Y axis, convex side out (0 = flat)272273varying vec2 vUv;274varying float vFacing;275276void main() {277 vUv = uv;278 vec3 p = position;279 vec3 n = vec3(0.0, 0.0, 1.0);280 if (uCurve > 0.0001) {281 float a = p.x * uCurve;282 p.x = sin(a) / uCurve;283 p.z = (cos(a) - 1.0) / uCurve;284 n = vec3(sin(a), 0.0, cos(a));285 }286 vec4 mvPosition = modelViewMatrix * vec4(p, 1.0);287 vFacing = abs(dot(normalize(normalMatrix * n), normalize(-mvPosition.xyz)));288 gl_Position = projectionMatrix * mvPosition;289}290`;291292const cardFragmentShader = /* glsl */ `293uniform sampler2D uMap;294uniform float uHasMap; // 1 once the texture is loaded295uniform float uReveal; // 0 → 1 fade from the placeholder to the image296uniform float uImageAspect;297uniform vec2 uSize; // card size in world units298uniform float uRadius; // corner radius in world units299uniform float uZoom; // > 1 crops into the image (headroom for parallax)300uniform vec2 uOffset; // image shift inside the card (parallax), in UV units301uniform float uBlur; // motion blur length, in UV units302uniform vec2 uBlurDir;303uniform float uOpacity;304uniform float uDim; // 0 = full brightness, 1 = black305uniform float uHover; // 0 → 1 highlight306uniform float uShade; // how much faces turned away from the camera darken307uniform float uTime;308uniform vec3 uTint; // placeholder color309310varying vec2 vUv;311varying float vFacing;312313// "object-fit: cover": the image fills the card without stretching314vec2 coverUv(vec2 uv) {315 float planeAspect = uSize.x / uSize.y;316 vec2 scale = planeAspect > uImageAspect ? vec2(1.0, uImageAspect / planeAspect) : vec2(planeAspect / uImageAspect, 1.0);317 return (uv - 0.5) * scale / uZoom + 0.5 + uOffset;318}319320float roundedMask(vec2 uv) {321 vec2 p = (uv - 0.5) * uSize;322 vec2 q = abs(p) - (uSize * 0.5 - uRadius);323 float d = length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - uRadius;324 float aa = fwidth(d);325 return 1.0 - smoothstep(-aa, aa, d);326}327328void main() {329 vec2 uv = vUv;330 // Seen from behind (a ring's far side), the image would be mirrored: flip it back331 if (!gl_FrontFacing) uv.x = 1.0 - uv.x;332333 float mask = roundedMask(vUv);334 float alpha = mask * uOpacity;335 if (alpha < 0.005) discard;336337 // Placeholder: dark tint with a sweeping shimmer while the texture loads338 float shimmer = pow(max(0.0, sin((vUv.x - vUv.y * 0.5) * 3.0 - uTime * 2.5)), 12.0);339 vec3 color = uTint + shimmer * 0.06;340341 if (uHasMap > 0.5) {342 vec2 imageUv = coverUv(uv);343 vec3 image;344 if (uBlur > 0.0005) {345 // Motion blur: 7 taps along the direction of travel346 image = vec3(0.0);347 for (int i = 0; i < 7; i++) {348 float t = (float(i) / 6.0 - 0.5) * uBlur;349 image += texture2D(uMap, imageUv + uBlurDir * t).rgb;350 }351 image /= 7.0;352 } else {353 image = texture2D(uMap, imageUv).rgb;354 }355 color = mix(color, image, uReveal);356 }357358 color *= mix(1.0, 0.35 + 0.65 * vFacing, uShade);359 color *= 1.0 - uDim;360 color += uHover * 0.07;361 gl_FragColor = vec4(color, alpha);362 #include <colorspace_fragment>363}364`;365366interface CardUniforms {367 uMap: THREE.IUniform<THREE.Texture | null>;368 uHasMap: THREE.IUniform<number>;369 uReveal: THREE.IUniform<number>;370 uImageAspect: THREE.IUniform<number>;371 uSize: THREE.IUniform<THREE.Vector2>;372 uRadius: THREE.IUniform<number>;373 uCurve: THREE.IUniform<number>;374 uZoom: THREE.IUniform<number>;375 uOffset: THREE.IUniform<THREE.Vector2>;376 uBlur: THREE.IUniform<number>;377 uBlurDir: THREE.IUniform<THREE.Vector2>;378 uOpacity: THREE.IUniform<number>;379 uDim: THREE.IUniform<number>;380 uHover: THREE.IUniform<number>;381 uShade: THREE.IUniform<number>;382 uTime: THREE.IUniform<number>;383 uTint: THREE.IUniform<THREE.Color>;384}385386function createCardMaterial() {387 const uniforms: CardUniforms = {388 uMap: { value: null },389 uHasMap: { value: 0 },390 uReveal: { value: 0 },391 uImageAspect: { value: 1 },392 uSize: { value: new THREE.Vector2(1, 1) },393 uRadius: { value: 0.06 },394 uCurve: { value: 0 },395 uZoom: { value: 1 },396 uOffset: { value: new THREE.Vector2() },397 uBlur: { value: 0 },398 uBlurDir: { value: new THREE.Vector2(0, 1) },399 uOpacity: { value: 1 },400 uDim: { value: 0 },401 uHover: { value: 0 },402 uShade: { value: 0 },403 uTime: { value: 0 },404 uTint: { value: new THREE.Color() },405 };406 return new THREE.ShaderMaterial({407 uniforms: uniforms as unknown as Record<string, THREE.IUniform>,408 vertexShader: cardVertexShader,409 fragmentShader: cardFragmentShader,410 transparent: true,411 side: THREE.DoubleSide,412 });413}414415/** Typed access to a card's uniforms from its mesh (galleries animate them in useFrame). */416function cardUniforms(mesh: THREE.Mesh) {417 return (mesh.material as THREE.ShaderMaterial).uniforms as unknown as CardUniforms;418}419420/** Plane sized in world units; enough columns to bend smoothly when the card is curved. */421function createCardGeometry(width: number, height: number, segments = 1) {422 return new THREE.PlaneGeometry(width, height, segments, 1);423}424425function TextureBinder({ url, material, onTexture }: { url: string; material: THREE.ShaderMaterial; onTexture?: (texture: THREE.Texture) => void }) {426 const texture = useTexture(url); // suspends until loaded; drei caches it per URL427 useLayoutEffect(() => {428 if (texture.colorSpace !== THREE.SRGBColorSpace) {429 texture.colorSpace = THREE.SRGBColorSpace;430 texture.needsUpdate = true;431 }432 texture.anisotropy = 4;433 const image = texture.image as { width?: number; height?: number } | undefined;434 const u = material.uniforms as unknown as CardUniforms;435 if (u.uMap.value !== texture) u.uReveal.value = 0; // fade in each new image436 u.uMap.value = texture;437 u.uImageAspect.value = image?.width && image?.height ? image.width / image.height : 1;438 u.uHasMap.value = 1;439 onTexture?.(texture);440 }, [texture, material, onTexture]);441 return null;442}443444/** A failed image keeps its placeholder instead of breaking the whole gallery. */445class TextureErrorBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {446 state = { failed: false };447 static getDerivedStateFromError() {448 return { failed: true };449 }450 render() {451 return this.state.failed ? null : this.props.children;452 }453}454455interface ImageCardProps extends Omit<ThreeElements["mesh"], "geometry" | "material" | "ref"> {456 url: string;457 width: number;458 height: number;459 /** Shared plane from createCardGeometry(width, height, segments). */460 geometry: THREE.BufferGeometry;461 radius?: number;462 /** 1 / radius of the surface the card is bent on (0 = flat). */463 curve?: number;464 /** 0–1: darken the card as it turns away from the camera. */465 shade?: number;466 zoom?: number;467 placeholderColor?: string;468 onTexture?: (texture: THREE.Texture) => void;469 ref?: Ref<THREE.Mesh>;470}471472/**473 * Image card: rounded corners, cover-fit image, placeholder shimmer while loading, fade-in once474 * loaded, placeholder kept if the image fails. Its material is created once and disposed on unmount.475 */476const ImageCard = memo(function ImageCard({477 url,478 width,479 height,480 geometry,481 radius = 0.06,482 curve = 0,483 shade = 0,484 zoom = 1,485 placeholderColor = "#151517",486 onTexture,487 ref,488 ...meshProps489}: ImageCardProps) {490 const material = useMemo(() => createCardMaterial(), []);491 const u = material.uniforms as unknown as CardUniforms;492493 useEffect(() => {494 u.uSize.value.set(width, height);495 u.uRadius.value = Math.min(radius, width / 2, height / 2);496 u.uCurve.value = curve;497 u.uShade.value = shade;498 u.uZoom.value = zoom;499 u.uTint.value.set(placeholderColor);500 }, [u, width, height, radius, curve, shade, zoom, placeholderColor]);501502 useEffect(() => () => material.dispose(), [material]);503504 useFrame((state, delta) => {505 if (u.uHasMap.value > 0.5) {506 if (u.uReveal.value < 0.999) u.uReveal.value = THREE.MathUtils.damp(u.uReveal.value, 1, 5, delta);507 } else {508 u.uTime.value = state.clock.elapsedTime;509 }510 });511512 return (513 // The shader bends the card: the plane's own bounds are not reliable for frustum culling514 <mesh ref={ref} geometry={geometry} material={material} frustumCulled={false} {...meshProps}>515 <TextureErrorBoundary key={url}>516 <Suspense fallback={null}>517 <TextureBinder url={url} material={material} onTexture={onTexture} />518 </Suspense>519 </TextureErrorBoundary>520 </mesh>521 );522});523524export interface SphereCloudProps extends Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {525 images: string[];526 /** Sphere radius in world units. Default 4. */527 radius?: number;528 /** Cards always face the camera (true) or lie on the sphere's surface (false). Default true. */529 billboard?: boolean;530 /** Clicking a card flies the camera in front of it; clicking the background flies back. Default true. */531 zoomOnSelect?: boolean;532}533534const CARD_WIDTH = 1.05;535const CARD_HEIGHT = 1.35;536const MIN_CARDS = 56;537const CLOSE_UP_DISTANCE = 2.6;538const GOLDEN_ANGLE = Math.PI * (3 - Math.sqrt(5));539540interface Flight {541 active: boolean;542 position: THREE.Vector3;543 target: THREE.Vector3;544}545546const Cloud = memo(function Cloud({ images, radius, billboard, zoomOnSelect }: Required<Omit<SphereCloudProps, "pauseWhenOffscreen" | "lowPowerMode">>) {547 const onTexture = useGalleryTextures(images);548 const cards = useMemo(() => cycleImages(images, MIN_CARDS), [images]);549 const cardRefs = useRef<(THREE.Mesh | null)[]>([]);550 const hovered = useRef(-1);551 const selected = useRef(-1);552 const controls = useThree((state) => state.controls) as OrbitControlsImpl | null;553 const reducedMotion = usePrefersReducedMotion();554 const flight = useRef<Flight>({ active: false, position: new THREE.Vector3(), target: new THREE.Vector3() });555 const scratch = useMemo(() => ({ outward: new THREE.Vector3(), world: new THREE.Vector3() }), []);556557 const geometry = useMemo(() => createCardGeometry(CARD_WIDTH, CARD_HEIGHT), []);558 useEffect(() => () => geometry.dispose(), [geometry]);559560 // Fibonacci sphere: evenly spread points, no clustering at the poles561 const points = useMemo(562 () =>563 cards.map((_, i) => {564 const y = 1 - ((i + 0.5) / cards.length) * 2;565 const r = Math.sqrt(1 - y * y);566 const theta = i * GOLDEN_ANGLE;567 return new THREE.Vector3(Math.cos(theta) * r, y, Math.sin(theta) * r).multiplyScalar(radius);568 }),569 [cards, radius]570 );571572 const select = (index: number) => {573 if (!zoomOnSelect) return;574 selected.current = index;575 const f = flight.current;576 f.target.copy(points[index]);577 f.position.copy(points[index]).normalize().multiplyScalar(radius + CLOSE_UP_DISTANCE);578 f.active = true;579 };580 const release = () => {581 if (selected.current === -1) return;582 selected.current = -1;583 const f = flight.current;584 const camera = controls?.object;585 if (!camera) return;586 // Back out along the current viewing direction, to the overview distance587 f.position.copy(camera.position).normalize().multiplyScalar(radius * 2.7);588 f.target.set(0, 0, 0);589 f.active = true;590 };591592 useFrame((state, delta) => {593 const dt = Math.min(delta, 1 / 30);594 const camera = state.camera;595596 // Smooth camera flight (lerp) towards the selected card, then hand control back to OrbitControls597 const f = flight.current;598 if (controls) {599 controls.autoRotate = !reducedMotion && selected.current === -1 && !f.active;600 if (f.active) {601 const k = 1 - Math.exp(-4 * dt);602 camera.position.lerp(f.position, k);603 controls.target.lerp(f.target, k);604 if (camera.position.distanceTo(f.position) < 0.01 && controls.target.distanceTo(f.target) < 0.01) f.active = false;605 controls.update();606 }607 }608609 cardRefs.current.forEach((mesh, i) => {610 if (!mesh) return;611 if (billboard) mesh.quaternion.copy(camera.quaternion);612 else mesh.lookAt(scratch.outward.copy(points[i]).multiplyScalar(2));613614 const u = cardUniforms(mesh);615 // Depth cue: the far side of the sphere is darker and fainter616 const distance = camera.position.distanceTo(mesh.getWorldPosition(scratch.world));617 const near = camera.position.length() - radius;618 const depth = THREE.MathUtils.clamp((distance - near) / (2 * radius), 0, 1);619 const focus = selected.current === -1 || selected.current === i ? 1 : 0.35;620 u.uDim.value = THREE.MathUtils.damp(u.uDim.value, 1 - (1 - depth * 0.75) * focus, 6, dt);621 u.uOpacity.value = 1 - depth * 0.55;622 const hover = THREE.MathUtils.damp(u.uHover.value, hovered.current === i ? 1 : 0, 10, dt);623 u.uHover.value = hover;624 mesh.scale.setScalar(1 + hover * 0.15);625 });626 });627628 // Click on the background flies back out, but releasing an orbit drag is not a click629 const gl = useThree((state) => state.gl);630 const pressedAt = useRef({ x: 0, y: 0 });631 useEffect(() => {632 const el = gl.domElement;633 const down = (event: PointerEvent) => {634 pressedAt.current = { x: event.clientX, y: event.clientY };635 };636 el.addEventListener("pointerdown", down);637 return () => el.removeEventListener("pointerdown", down);638 }, [gl]);639 const onMissed = (event: MouseEvent) => {640 if (Math.hypot(event.clientX - pressedAt.current.x, event.clientY - pressedAt.current.y) < 6) release();641 };642643 return (644 <group onPointerMissed={onMissed}>645 {cards.map((url, i) => (646 <ImageCard647 key={i}648 ref={(mesh) => {649 cardRefs.current[i] = mesh;650 }}651 url={url}652 width={CARD_WIDTH}653 height={CARD_HEIGHT}654 geometry={geometry}655 radius={0.08}656 position={points[i]}657 onTexture={onTexture}658 onPointerOver={(e: ThreeEvent<PointerEvent>) => {659 e.stopPropagation();660 hovered.current = i;661 document.body.style.cursor = "pointer";662 }}663 onPointerOut={() => {664 if (hovered.current === i) hovered.current = -1;665 document.body.style.cursor = "";666 }}667 onClick={(e: ThreeEvent<MouseEvent>) => {668 e.stopPropagation();669 if (e.delta > 6) return; // an orbit drag is not a click670 if (selected.current === i) release();671 else select(i);672 }}673 />674 ))}675 </group>676 );677});678679function SphereCloudGallery({ images, radius = 4, billboard = true, zoomOnSelect = true, pauseWhenOffscreen, lowPowerMode }: SphereCloudProps) {680 return (681 <GalleryCanvas pauseWhenOffscreen={pauseWhenOffscreen} lowPowerMode={lowPowerMode} captureWheel touchAction="none" camera={{ position: [0, 0, radius * 2.7], fov: 45, near: 0.1, far: radius * 12 }}>682 <OrbitControls makeDefault enablePan={false} enableDamping dampingFactor={0.08} autoRotateSpeed={0.6} minDistance={1.2} maxDistance={radius * 4} />683 <Cloud images={images} radius={radius} billboard={billboard} zoomOnSelect={zoomOnSelect} />684 </GalleryCanvas>685 );686}687688export default memo(SphereCloudGallery);
03
Drop it in a page
Updated live with the settings above.
app/page.tsx
1import SphereCloudGallery from "@/components/SphereCloudGallery";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 <SphereCloudGallery8 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}23 />24 </div>25 );26}