← All components Next componentAurora Gradient→
Background · Instanced
Floating Shapes
A tilted galaxy of iridescent chrome cubes, tori and gems orbiting in a studio light. Hover to push, click to send a shockwave.
<FloatingShapesBackground />Live
Move or click to push them away
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 floating-shapes
01
Install
The 3D packages this component is built on.
$ npm install three @react-three/fiber @react-three/drei @react-three/postprocessing postprocessing && npm install -D @types/three
02
Add the component
One self-contained file: create components/FloatingShapesBackground.tsx and paste it in.
components/FloatingShapesBackground.tsx
1"use client";23import {4 memo,5 useCallback,6 useEffect,7 useLayoutEffect,8 useMemo,9 useRef,10 useState,11 type CSSProperties,12 type ReactNode,13 type RefObject,14} from "react";15import * as THREE from "three";16import { RoundedBoxGeometry } from "three/examples/jsm/geometries/RoundedBoxGeometry.js";17import { Canvas, useFrame, useThree, type CanvasProps } from "@react-three/fiber";18import { Environment, Lightformer } from "@react-three/drei";19import { Bloom, EffectComposer, Vignette } from "@react-three/postprocessing";2021/**22 * The shared props API of DeepUI's individual 3D components (not the full-page templates, which keep23 * their own tailored scenes).24 *25 * The props are grouped by concern. A component extends ONLY the groups it really applies, so its26 * type never advertises a knob that does nothing (a card has no particles, a background has no tilt):27 *28 * interface MyCardProps extends CursorProps, TiltProps, MaterialProps, PerformanceProps { … }29 *30 * `Base3DComponentProps` is every group at once, for tooling that handles any component. Same name,31 * same unit and same meaning everywhere; the default values live in DEFAULT_3D_PROPS. These files are32 * inlined into each component's single-file bundle (lib/bundle-source.mjs), only what it uses.33 */3435/** Which rotation axes follow the pointer. "x-only": the object nods (up / down); "y-only": it turns (left / right). */36export type TiltAxis = "both" | "x-only" | "y-only" | "none";3738/** 1. Cursor: how the pointer pulls, pushes and drags the object. */39interface CursorProps {40 /** 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). */41 cursorRadius?: number;42 /** Positive pulls things towards the pointer, negative pushes them away (repulsion, shockwave). Default 1. */43 cursorForce?: number;44 /** How far the object slides towards the pointer, 0 (stays put) to 1 (follows closely). Default 0. */45 magneticStrength?: number;46 /** Share of the remaining distance the motion closes each frame (at 60 fps), 0.01 (heavy, slow) to 1 (instant). Default 0.1. */47 cursorDamping?: number;48}4950/** 2. Tilt and parallax: the object leans towards the pointer, its layers slide against each other. */51interface TiltProps {52 /** Largest lean towards the pointer, in degrees. Default 15. */53 maxTiltAngle?: number;54 /** Axes that follow the pointer. Default "both". */55 tiltAxis?: TiltAxis;56 /** Lean away from the pointer instead of towards it. Default false. */57 invertTilt?: boolean;58 /** How far apart the depth layers slide when the object tilts, 0 (flat) to 2. Default 1. */59 parallaxOffset?: number;60}6162/** 3. Text and 3D typography, for components that draw a label. */63interface Text3DProps {64 /** The label drawn by the component. */65 text?: string;66 /** Scale of the lettering. Default 1. */67 fontSize?: number;68 /** Extrusion depth of 3D letters. Default 0.2. */69 textDepth?: number;70 /** Bevelled, light-catching edges on 3D letters. Default true. */71 bevelEnabled?: boolean;72 /** Custom font: a .woff / .ttf (flat text) or a typeface .json (extruded text). */73 fontUrl?: string;74}7576/** 4. Rendering, materials and glow. */77interface MaterialProps {78 /** Main color of the object. Default "#6366f1". */79 primaryColor?: string;80 /** Color of the glow. Default "#00f0ff". */81 emissiveColor?: string;82 /** Strength of the glow, 0 (none) to 3. Default 1. */83 emissiveIntensity?: number;84 /** 0 (mirror, glass) to 1 (matte). Default 0.3. */85 roughness?: number;86 /** 0 (plastic, organic) to 1 (metal). Default 0.5. */87 metalness?: number;88 /** 0 (opaque) to 1 (clear glass): see-through, refracting surfaces. Default 0. */89 transmission?: number;90 /** Technical wireframe rendering. Default false. */91 wireframe?: boolean;92}9394/** 5. Particles, idle motion and shader animation. */95interface MotionProps {96 /** Number of instanced elements. Default depends on the component. */97 particleCount?: number;98 /** Spin on its own, in radians per second (negative: the other way; 0.5 ≈ one turn in 12 s). Default 0. */99 autoRotateSpeed?: number;100 /** Pulses or ripples per second. Default 1. */101 pulseRate?: number;102 /** Amplitude of the noise deformation, 0 (none) to 2. Default 1. */103 displacementScale?: number;104}105106/** 6. Environment and camera. */107interface EnvironmentProps {108 /** Camera field of view, in degrees. Default depends on the component. */109 cameraFov?: number;110 /** Color of the depth fog. Default "#0a0a0a". */111 fogColor?: string;112 /** Thickness of the fog, 0 (none) to 0.2. Default 0. */113 fogDensity?: number;114}115116/** 7. Performance and accessibility. */117interface PerformanceProps {118 /** Lighter rendering for weak devices: pixel ratio 1, fewer instances, smaller environment maps. Default false. */119 lowPowerMode?: boolean;120 /** Under the OS "reduce motion" setting, stop idle spin, pulses and deformation (pointer feedback stays). Default true. */121 respectReducedMotion?: boolean;122 /** Stop the render loop while the component is scrolled out of view. Default true. */123 pauseWhenOffscreen?: boolean;124}125126/** Every group at once. Components extend only the groups they apply (see the top of this file). */127interface Base3DComponentProps128 extends CursorProps,129 TiltProps,130 Text3DProps,131 MaterialProps,132 MotionProps,133 EnvironmentProps,134 PerformanceProps {}135136type Defaults = Required<Omit<Base3DComponentProps, "text" | "fontUrl" | "particleCount" | "cameraFov">>;137138/** The values a prop takes when it is left out. A component may override one, and then documents it. */139const DEFAULT_3D_PROPS: Defaults = {140 cursorRadius: 220,141 cursorForce: 1,142 magneticStrength: 0,143 cursorDamping: 0.1,144 maxTiltAngle: 15,145 tiltAxis: "both",146 invertTilt: false,147 parallaxOffset: 1,148 fontSize: 1,149 textDepth: 0.2,150 bevelEnabled: true,151 primaryColor: "#6366f1",152 emissiveColor: "#00f0ff",153 emissiveIntensity: 1,154 roughness: 0.3,155 metalness: 0.5,156 transmission: 0,157 wireframe: false,158 autoRotateSpeed: 0,159 pulseRate: 1,160 displacementScale: 1,161 fogColor: "#0a0a0a",162 fogDensity: 0,163 lowPowerMode: false,164 respectReducedMotion: true,165 pauseWhenOffscreen: true,166};167168/** Fills the positioned parent; never intercepts clicks meant for the page content above it. */169const FILL_STYLE: CSSProperties = {170 position: "absolute",171 top: 0,172 left: 0,173 width: "100%",174 height: "100%",175 pointerEvents: "none",176};177178interface BackgroundCanvasProps extends Omit<CanvasProps, "children" | "style" | "frameloop" | "gl">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {179 children: ReactNode;180}181182/**183 * Ready-to-use <Canvas> shared by every background.184 * - Pauses the render loop while the canvas is scrolled out of view.185 * - Renders a single still frame when the user prefers reduced motion.186 * - Caps the pixel ratio; R3F disposes the renderer and releases the WebGL187 * context (forceContextLoss) when the Canvas unmounts.188 */189function BackgroundCanvas({ children, dpr = [1, 1.75], pauseWhenOffscreen = DEFAULT_3D_PROPS.pauseWhenOffscreen, lowPowerMode = DEFAULT_3D_PROPS.lowPowerMode, ...canvasProps }: BackgroundCanvasProps) {190 const containerRef = useRef<HTMLDivElement>(null);191 // Starts "in view" so the first frame is always drawn before the loop can be paused192 const [inView, setInView] = useState(true);193 const [reducedMotion, setReducedMotion] = useState(false);194195 useEffect(() => {196 const el = containerRef.current;197 if (!el) return undefined;198 const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting));199 observer.observe(el);200201 const query = window.matchMedia("(prefers-reduced-motion: reduce)");202 const sync = () => setReducedMotion(query.matches);203 sync();204 query.addEventListener("change", sync);205206 return () => {207 observer.disconnect();208 query.removeEventListener("change", sync);209 };210 }, []);211212 return (213 <div ref={containerRef} style={FILL_STYLE} aria-hidden="true">214 <Canvas215 dpr={lowPowerMode ? 1 : dpr}216 frameloop={!inView && pauseWhenOffscreen ? "never" : reducedMotion ? "demand" : "always"}217 gl={{ antialias: true, alpha: true, powerPreference: "high-performance" }}218 style={{ pointerEvents: "none" }}219 {...canvasProps}220 >221 {children}222 </Canvas>223 </div>224 );225}226227interface CanvasPointer {228 /** Pointer position in normalized device coordinates of the canvas (-1..1). */229 ndc: THREE.Vector2;230 /** True while the pointer is over the canvas area. */231 inside: boolean;232 /** True while a button is held down. */233 pressed: boolean;234}235236/**237 * Tracks the pointer relative to the canvas through window listeners: the238 * canvas itself has `pointer-events: none`, so R3F's own events never fire.239 * Returns a ref read inside useFrame — pointer moves never re-render React.240 */241function useCanvasPointer(onDown?: (ndc: THREE.Vector2) => void): RefObject<CanvasPointer> {242 const gl = useThree((state) => state.gl);243 const pointer = useRef<CanvasPointer>({ ndc: new THREE.Vector2(), inside: false, pressed: false });244 const onDownRef = useRef(onDown);245246 useEffect(() => {247 onDownRef.current = onDown;248 }, [onDown]);249250 useEffect(() => {251 const el = gl.domElement;252 const update = (event: PointerEvent) => {253 const rect = el.getBoundingClientRect();254 const p = pointer.current;255 p.ndc.set(((event.clientX - rect.left) / rect.width) * 2 - 1, -((event.clientY - rect.top) / rect.height) * 2 + 1);256 p.inside = Math.abs(p.ndc.x) <= 1 && Math.abs(p.ndc.y) <= 1;257 };258 const down = (event: PointerEvent) => {259 update(event);260 pointer.current.pressed = true;261 if (pointer.current.inside) onDownRef.current?.(pointer.current.ndc);262 };263 const up = () => {264 pointer.current.pressed = false;265 };266 const leave = () => {267 pointer.current.inside = false;268 pointer.current.pressed = false;269 };270271 window.addEventListener("pointermove", update, { passive: true });272 window.addEventListener("pointerdown", down, { passive: true });273 window.addEventListener("pointerup", up, { passive: true });274 document.documentElement.addEventListener("pointerleave", leave);275 window.addEventListener("blur", leave);276 return () => {277 window.removeEventListener("pointermove", update);278 window.removeEventListener("pointerdown", down);279 window.removeEventListener("pointerup", up);280 document.documentElement.removeEventListener("pointerleave", leave);281 window.removeEventListener("blur", leave);282 };283 }, [gl]);284285 return pointer;286}287288export type FloatingShape = "cube" | "torus" | "icosahedron";289290export interface FloatingShapesProps extends Pick<MaterialProps, "roughness" | "metalness">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {291 /** Instances per shape type (one draw call per type). Default 80. */292 instanceCountPerShape?: number;293 shapes?: FloatingShape[];294 /** Tints of the instances; they also color the studio lights reflected by the chrome. */295 colorPalette?: string[];296 roughness?: number;297 metalness?: number;298 /** Speed multiplier of the orbit and floating motion. Default 1. */299 floatSpeed?: number;300}301302const DEFAULT_SHAPES: FloatingShape[] = ["cube", "torus", "icosahedron"];303const DEFAULT_PALETTE = ["#ffffff", "#dbe4ff", "#f5d0fe", "#a5f3fc"];304305const DISC_RADIUS = 11; // outer radius of the galaxy306const HOVER_RADIUS = 1.8;307const CLICK_RADIUS = 4;308const SPRING = 5; // pull back to the orbit309const DAMPING = 2.2;310311function createGeometry(shape: FloatingShape): THREE.BufferGeometry {312 switch (shape) {313 case "cube":314 // Rounded edges catch a thin highlight that a sharp box never shows315 return new RoundedBoxGeometry(1, 1, 1, 4, 0.12);316 case "torus":317 return new THREE.TorusGeometry(0.5, 0.2, 32, 96);318 case "icosahedron":319 return new THREE.IcosahedronGeometry(0.68, 0);320 }321}322323interface ClickState {324 id: number;325 ndc: THREE.Vector2;326}327328interface ShapeLayerProps {329 shape: FloatingShape;330 count: number;331 palette: string[];332 roughness: number;333 metalness: number;334 floatSpeed: number;335 pointer: RefObject<CanvasPointer>;336 clicks: RefObject<ClickState>;337}338339const ShapeLayer = memo(function ShapeLayer({ shape, count, palette, roughness, metalness, floatSpeed, pointer, clicks }: ShapeLayerProps) {340 const meshRef = useRef<THREE.InstancedMesh>(null);341 const lastClick = useRef(0);342343 const geometry = useMemo(() => createGeometry(shape), [shape]);344 // Polished chrome with a clearcoat and a thin-film (soap bubble) sheen that shifts with the viewing angle345 const material = useMemo(346 () =>347 new THREE.MeshPhysicalMaterial({348 color: 0xffffff,349 clearcoat: 1,350 clearcoatRoughness: 0.08,351 iridescence: 0.7,352 iridescenceIOR: 1.45,353 iridescenceThicknessRange: [180, 620],354 envMapIntensity: 2.2,355 flatShading: shape === "icosahedron", // faceted gem: each face mirrors a different light356 }),357 [shape]358 );359360 // Per-instance state in flat typed arrays: no per-instance objects to allocate or collect361 const data = useMemo(() => {362 const radius = new Float32Array(count);363 const angle = new Float32Array(count);364 const height = new Float32Array(count);365 const orbit = new Float32Array(count);366 const bob = new Float32Array(count * 2); // frequency, phase367 const axis = new Float32Array(count * 3);368 const spin = new Float32Array(count);369 const rotation = new Float32Array(count);370 const spinBoost = new Float32Array(count); // extra spin from cursor hits, decays371 const scale = new Float32Array(count);372 const offset = new Float32Array(count * 3); // displacement caused by the cursor373 const velocity = new Float32Array(count * 3);374 const v = new THREE.Vector3();375 for (let i = 0; i < count; i++) {376 // Denser towards the center, like a galaxy377 const r = 1.6 + Math.pow(Math.random(), 0.8) * (DISC_RADIUS - 1.6);378 radius[i] = r;379 angle[i] = Math.random() * Math.PI * 2;380 // Thicker disc near the core, flatter at the rim381 height[i] = (Math.random() * 2 - 1) * (2.6 - (r / DISC_RADIUS) * 1.6);382 // Inner orbits turn faster (Keplerian falloff)383 orbit[i] = 0.55 / Math.sqrt(r);384 bob[i * 2] = 0.4 + Math.random() * 0.6;385 bob[i * 2 + 1] = Math.random() * Math.PI * 2;386 v.set(Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5).normalize();387 axis[i * 3] = v.x;388 axis[i * 3 + 1] = v.y;389 axis[i * 3 + 2] = v.z;390 spin[i] = (0.15 + Math.random() * 0.5) * (Math.random() < 0.5 ? -1 : 1);391 rotation[i] = Math.random() * Math.PI * 2;392 // Mostly small debris, a few large hero pieces393 scale[i] = 0.18 + Math.pow(Math.random(), 4) * 0.95;394 }395 return { radius, angle, height, orbit, bob, axis, spin, rotation, spinBoost, scale, offset, velocity };396 }, [count]);397398 // Scratch objects reused every frame399 const scratch = useMemo(400 () => ({401 matrix: new THREE.Matrix4(),402 position: new THREE.Vector3(),403 world: new THREE.Vector3(),404 quaternion: new THREE.Quaternion(),405 scale: new THREE.Vector3(),406 axis: new THREE.Vector3(),407 closest: new THREE.Vector3(),408 push: new THREE.Vector3(),409 hoverRay: new THREE.Raycaster(),410 clickRay: new THREE.Raycaster(),411 }),412 []413 );414415 useEffect(() => {416 material.roughness = roughness;417 material.metalness = metalness;418 }, [material, roughness, metalness]);419420 const paletteKey = palette.join("|");421 useLayoutEffect(() => {422 const mesh = meshRef.current;423 if (!mesh) return;424 mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);425 const color = new THREE.Color();426 const colors = paletteKey ? paletteKey.split("|") : ["#ffffff"];427 for (let i = 0; i < count; i++) {428 mesh.setColorAt(i, color.set(colors[Math.floor(Math.random() * colors.length)]));429 }430 if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;431 }, [count, paletteKey]);432433 useEffect(() => () => geometry.dispose(), [geometry]);434 useEffect(() => () => material.dispose(), [material]);435 useEffect(() => {436 const mesh = meshRef.current;437 // Releases the instance matrix / color buffers438 return () => mesh?.dispose();439 }, [count]);440441 useFrame((state, delta) => {442 const mesh = meshRef.current;443 if (!mesh) return;444 const dt = Math.min(delta, 1 / 30);445 const t = state.clock.elapsedTime * floatSpeed;446 const { radius, angle, height, orbit, bob, axis, spin, rotation, spinBoost, scale, offset, velocity } = data;447 const { matrix, position, world, quaternion, scale: scaleVec, closest, push, hoverRay, clickRay } = scratch;448449 // The galaxy is tilted by the parent group: cursor tests run in world space, motion in local space450 const parent = mesh.parent;451 const p = pointer.current;452 if (p.inside) hoverRay.setFromCamera(p.ndc, state.camera);453 const click = clicks.current;454 const clicked = click.id !== lastClick.current;455 if (clicked) {456 lastClick.current = click.id;457 clickRay.setFromCamera(click.ndc, state.camera);458 }459460 const damping = Math.exp(-DAMPING * dt);461 const spinDecay = Math.exp(-1.5 * dt);462 for (let i = 0; i < count; i++) {463 const i3 = i * 3;464 const a = angle[i] + t * orbit[i];465 position.set(466 Math.cos(a) * radius[i] + offset[i3],467 height[i] + Math.sin(t * bob[i * 2] + bob[i * 2 + 1]) * 0.35 + offset[i3 + 1],468 Math.sin(a) * radius[i] + offset[i3 + 2]469 );470471 const hover = p.inside;472 if (hover || clicked) {473 world.copy(position);474 if (parent) parent.localToWorld(world);475476 // Hover: continuous soft push away from the cursor ray, plus a little spin477 if (hover) {478 hoverRay.ray.closestPointToPoint(world, closest);479 push.subVectors(world, closest);480 const dist = push.length();481 if (dist < HOVER_RADIUS) {482 if (dist < 1e-4) push.set(0, 1, 0);483 const strength = 1 - dist / HOVER_RADIUS;484 push.normalize().multiplyScalar(strength * 16 * dt);485 velocity[i3] += push.x;486 velocity[i3 + 1] += push.y;487 velocity[i3 + 2] += push.z;488 spinBoost[i] += strength * 6 * dt;489 }490 }491492 // Click: shockwave that scatters and spins everything near the clicked point493 if (clicked) {494 clickRay.ray.closestPointToPoint(world, closest);495 push.subVectors(world, closest);496 const dist = push.length();497 if (dist < CLICK_RADIUS) {498 if (dist < 1e-4) push.set(Math.random() - 0.5, Math.random() - 0.5, 0);499 const strength = 1 - dist / CLICK_RADIUS;500 push.normalize().multiplyScalar(strength * (8 + Math.random() * 5));501 velocity[i3] += push.x;502 velocity[i3 + 1] += push.y;503 velocity[i3 + 2] += push.z;504 spinBoost[i] += strength * (6 + Math.random() * 6);505 }506 }507 }508509 // Damped spring back to the orbit510 for (let k = 0; k < 3; k++) {511 velocity[i3 + k] = (velocity[i3 + k] - offset[i3 + k] * SPRING * dt) * damping;512 offset[i3 + k] += velocity[i3 + k] * dt;513 }514515 spinBoost[i] *= spinDecay;516 rotation[i] += (spin[i] * floatSpeed + spinBoost[i]) * dt;517 scratch.axis.set(axis[i3], axis[i3 + 1], axis[i3 + 2]);518 quaternion.setFromAxisAngle(scratch.axis, rotation[i]);519 scaleVec.setScalar(scale[i]);520 mesh.setMatrixAt(i, matrix.compose(position, quaternion, scaleVec));521 }522 mesh.instanceMatrix.needsUpdate = true;523 });524525 // key: a new count needs new instance buffers526 return <instancedMesh key={count} ref={meshRef} args={[geometry, material, count]} frustumCulled={false} />;527});528529/** Camera drifts towards the cursor: the whole galaxy reacts with depth parallax. */530function CameraRig({ pointer }: { pointer: RefObject<CanvasPointer> }) {531 useFrame((state, delta) => {532 const p = pointer.current;533 const targetX = p.inside ? p.ndc.x * 1.6 : 0;534 const targetY = 2.2 + (p.inside ? p.ndc.y * 1.0 : 0);535 state.camera.position.x = THREE.MathUtils.damp(state.camera.position.x, targetX, 2, delta);536 state.camera.position.y = THREE.MathUtils.damp(state.camera.position.y, targetY, 2, delta);537 state.camera.lookAt(0, 0, 0);538 });539 return null;540}541542type ShapesSceneProps = Required<Omit<FloatingShapesProps, "pauseWhenOffscreen" | "lowPowerMode">>;543544const ShapesScene = memo(function ShapesScene({545 instanceCountPerShape,546 shapes,547 colorPalette,548 roughness,549 metalness,550 floatSpeed,551}: ShapesSceneProps) {552 const clicks = useRef<ClickState>({ id: 0, ndc: new THREE.Vector2() });553 const onDown = useCallback((ndc: THREE.Vector2) => {554 clicks.current.ndc.copy(ndc);555 clicks.current.id += 1;556 }, []);557 const pointer = useCanvasPointer(onDown);558559 // Stable identities, so inline array props don't rebuild anything on re-render560 const shapesKey = shapes.join(",");561 const uniqueShapes = useMemo(() => Array.from(new Set(shapesKey.split(","))) as FloatingShape[], [shapesKey]);562 const paletteKey = colorPalette.join("|");563 const palette = useMemo(() => paletteKey.split("|"), [paletteKey]);564 // Two accent lights take their color from the palette, so the chrome reflects the brand colors565 const accentA = palette[2] ?? palette[0] ?? "#ffffff";566 const accentB = palette[3] ?? palette[1] ?? "#ffffff";567568 return (569 <>570 <CameraRig pointer={pointer} />571 <fog attach="fog" args={["#000000", 12, 30]} />572 <ambientLight intensity={0.15} />573 <spotLight position={[6, 10, 8]} angle={0.5} penumbra={1} intensity={120} distance={40} />574575 {/* Studio built from light panels: no HDR file to download */}576 <Environment resolution={256} frames={1}>577 {/* Soft ceiling and dim surround: no reflection ever falls to pure black */}578 <Lightformer form="rect" intensity={1.2} position={[0, 9, 0]} rotation-x={Math.PI / 2} scale={[30, 30, 1]} />579 <Lightformer form="rect" intensity={0.25} position={[0, 0, -12]} scale={[40, 20, 1]} />580 {/* Vertical strips all around: the long crisp highlights that read as chrome */}581 {[-9, -3, 3, 9].map((x, i) => (582 <Lightformer key={x} form="rect" intensity={i % 2 ? 5 : 3} position={[x, 0, 6]} scale={[0.6, 14, 1]} />583 ))}584 <Lightformer form="rect" intensity={4} color={accentA} position={[-10, 1, 0]} rotation-y={Math.PI / 2} scale={[12, 5, 1]} />585 <Lightformer form="rect" intensity={4} color={accentB} position={[10, -1, 0]} rotation-y={-Math.PI / 2} scale={[12, 5, 1]} />586 <Lightformer form="ring" intensity={8} position={[0, 3, 10]} scale={4} />587 </Environment>588589 {/* Tilted galaxy, slowly orbiting its own axis */}590 <group rotation={[0.42, 0, -0.18]}>591 {uniqueShapes.map((shape) => (592 <ShapeLayer593 key={shape}594 shape={shape}595 count={Math.max(1, Math.round(instanceCountPerShape))}596 palette={palette}597 roughness={roughness}598 metalness={metalness}599 floatSpeed={floatSpeed}600 pointer={pointer}601 clicks={clicks}602 />603 ))}604 </group>605 </>606 );607});608609function FloatingShapesBackground({610 instanceCountPerShape = 80,611 shapes = DEFAULT_SHAPES,612 colorPalette = DEFAULT_PALETTE,613 roughness = 0.12,614 metalness = 0.9,615 floatSpeed = 1,616 pauseWhenOffscreen,617 lowPowerMode,618}: FloatingShapesProps) {619 return (620 <BackgroundCanvas pauseWhenOffscreen={pauseWhenOffscreen} lowPowerMode={lowPowerMode} camera={{ position: [0, 2.2, 14], fov: 45 }}>621 <ShapesScene622 instanceCountPerShape={instanceCountPerShape}623 shapes={shapes}624 colorPalette={colorPalette}625 roughness={roughness}626 metalness={metalness}627 floatSpeed={floatSpeed}628 />629 <EffectComposer multisampling={4}>630 <Bloom mipmapBlur intensity={0.7} luminanceThreshold={0.75} luminanceSmoothing={0.2} />631 <Vignette offset={0.25} darkness={0.75} />632 </EffectComposer>633 </BackgroundCanvas>634 );635}636637export default memo(FloatingShapesBackground);
03
Drop it in a page
Updated live with the settings above.
app/page.tsx
1import FloatingShapesBackground from "@/components/FloatingShapesBackground";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 <FloatingShapesBackground8 instanceCountPerShape={80}9 floatSpeed={1}10 roughness={0.12}11 metalness={0.9}12 />13 </div>14 );15}