Loading…
← All components

Background · Space

Hyperspace Starfield

Thousands of stars streaking towards the camera; scrolling triggers the jump to hyperspace.

<HyperspaceStarfieldBackground />Live

Customize

Stars#cfe3ff

Installation

Use it in your project

Or skip the copy-paste

One command: writes the file and installs the dependencies.

$ npx deepui-cli add hyperspace-starfield
01

Install

The 3D packages this component is built on.

$ npm install three @react-three/fiber @react-three/postprocessing postprocessing && npm install -D @types/three
02

Add the component

One self-contained file: create components/HyperspaceStarfieldBackground.tsx and paste it in.

components/HyperspaceStarfieldBackground.tsx
1"use client";
2
3import {
4 memo,
5 useEffect,
6 useMemo,
7 useRef,
8 useState,
9 type CSSProperties,
10 type ReactNode,
11 type RefObject,
12} from "react";
13import * as THREE from "three";
14import { Canvas, useFrame, type CanvasProps } from "@react-three/fiber";
15import { Bloom, ChromaticAberration, EffectComposer, Vignette } from "@react-three/postprocessing";
16import type { ChromaticAberrationEffect } from "postprocessing";
17
18/**
19 * The shared props API of DeepUI's individual 3D components (not the full-page templates, which keep
20 * their own tailored scenes).
21 *
22 * The props are grouped by concern. A component extends ONLY the groups it really applies, so its
23 * type never advertises a knob that does nothing (a card has no particles, a background has no tilt):
24 *
25 * interface MyCardProps extends CursorProps, TiltProps, MaterialProps, PerformanceProps { … }
26 *
27 * `Base3DComponentProps` is every group at once, for tooling that handles any component. Same name,
28 * same unit and same meaning everywhere; the default values live in DEFAULT_3D_PROPS. These files are
29 * inlined into each component's single-file bundle (lib/bundle-source.mjs), only what it uses.
30 */
31
32/** Which rotation axes follow the pointer. "x-only": the object nods (up / down); "y-only": it turns (left / right). */
33export type TiltAxis = "both" | "x-only" | "y-only" | "none";
34
35/** 1. Cursor: how the pointer pulls, pushes and drags the object. */
36interface CursorProps {
37 /** 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). */
38 cursorRadius?: number;
39 /** Positive pulls things towards the pointer, negative pushes them away (repulsion, shockwave). Default 1. */
40 cursorForce?: number;
41 /** How far the object slides towards the pointer, 0 (stays put) to 1 (follows closely). Default 0. */
42 magneticStrength?: number;
43 /** Share of the remaining distance the motion closes each frame (at 60 fps), 0.01 (heavy, slow) to 1 (instant). Default 0.1. */
44 cursorDamping?: number;
45}
46
47/** 2. Tilt and parallax: the object leans towards the pointer, its layers slide against each other. */
48interface TiltProps {
49 /** Largest lean towards the pointer, in degrees. Default 15. */
50 maxTiltAngle?: number;
51 /** Axes that follow the pointer. Default "both". */
52 tiltAxis?: TiltAxis;
53 /** Lean away from the pointer instead of towards it. Default false. */
54 invertTilt?: boolean;
55 /** How far apart the depth layers slide when the object tilts, 0 (flat) to 2. Default 1. */
56 parallaxOffset?: number;
57}
58
59/** 3. Text and 3D typography, for components that draw a label. */
60interface Text3DProps {
61 /** The label drawn by the component. */
62 text?: string;
63 /** Scale of the lettering. Default 1. */
64 fontSize?: number;
65 /** Extrusion depth of 3D letters. Default 0.2. */
66 textDepth?: number;
67 /** Bevelled, light-catching edges on 3D letters. Default true. */
68 bevelEnabled?: boolean;
69 /** Custom font: a .woff / .ttf (flat text) or a typeface .json (extruded text). */
70 fontUrl?: string;
71}
72
73/** 4. Rendering, materials and glow. */
74interface MaterialProps {
75 /** Main color of the object. Default "#6366f1". */
76 primaryColor?: string;
77 /** Color of the glow. Default "#00f0ff". */
78 emissiveColor?: string;
79 /** Strength of the glow, 0 (none) to 3. Default 1. */
80 emissiveIntensity?: number;
81 /** 0 (mirror, glass) to 1 (matte). Default 0.3. */
82 roughness?: number;
83 /** 0 (plastic, organic) to 1 (metal). Default 0.5. */
84 metalness?: number;
85 /** 0 (opaque) to 1 (clear glass): see-through, refracting surfaces. Default 0. */
86 transmission?: number;
87 /** Technical wireframe rendering. Default false. */
88 wireframe?: boolean;
89}
90
91/** 5. Particles, idle motion and shader animation. */
92interface MotionProps {
93 /** Number of instanced elements. Default depends on the component. */
94 particleCount?: number;
95 /** Spin on its own, in radians per second (negative: the other way; 0.5 ≈ one turn in 12 s). Default 0. */
96 autoRotateSpeed?: number;
97 /** Pulses or ripples per second. Default 1. */
98 pulseRate?: number;
99 /** Amplitude of the noise deformation, 0 (none) to 2. Default 1. */
100 displacementScale?: number;
101}
102
103/** 6. Environment and camera. */
104interface EnvironmentProps {
105 /** Camera field of view, in degrees. Default depends on the component. */
106 cameraFov?: number;
107 /** Color of the depth fog. Default "#0a0a0a". */
108 fogColor?: string;
109 /** Thickness of the fog, 0 (none) to 0.2. Default 0. */
110 fogDensity?: number;
111}
112
113/** 7. Performance and accessibility. */
114interface PerformanceProps {
115 /** Lighter rendering for weak devices: pixel ratio 1, fewer instances, smaller environment maps. Default false. */
116 lowPowerMode?: boolean;
117 /** Under the OS "reduce motion" setting, stop idle spin, pulses and deformation (pointer feedback stays). Default true. */
118 respectReducedMotion?: boolean;
119 /** Stop the render loop while the component is scrolled out of view. Default true. */
120 pauseWhenOffscreen?: boolean;
121}
122
123/** Every group at once. Components extend only the groups they apply (see the top of this file). */
124interface Base3DComponentProps
125 extends CursorProps,
126 TiltProps,
127 Text3DProps,
128 MaterialProps,
129 MotionProps,
130 EnvironmentProps,
131 PerformanceProps {}
132
133type Defaults = Required<Omit<Base3DComponentProps, "text" | "fontUrl" | "particleCount" | "cameraFov">>;
134
135/** The values a prop takes when it is left out. A component may override one, and then documents it. */
136const DEFAULT_3D_PROPS: Defaults = {
137 cursorRadius: 220,
138 cursorForce: 1,
139 magneticStrength: 0,
140 cursorDamping: 0.1,
141 maxTiltAngle: 15,
142 tiltAxis: "both",
143 invertTilt: false,
144 parallaxOffset: 1,
145 fontSize: 1,
146 textDepth: 0.2,
147 bevelEnabled: true,
148 primaryColor: "#6366f1",
149 emissiveColor: "#00f0ff",
150 emissiveIntensity: 1,
151 roughness: 0.3,
152 metalness: 0.5,
153 transmission: 0,
154 wireframe: false,
155 autoRotateSpeed: 0,
156 pulseRate: 1,
157 displacementScale: 1,
158 fogColor: "#0a0a0a",
159 fogDensity: 0,
160 lowPowerMode: false,
161 respectReducedMotion: true,
162 pauseWhenOffscreen: true,
163};
164
165/** Fills the positioned parent; never intercepts clicks meant for the page content above it. */
166const FILL_STYLE: CSSProperties = {
167 position: "absolute",
168 top: 0,
169 left: 0,
170 width: "100%",
171 height: "100%",
172 pointerEvents: "none",
173};
174
175interface BackgroundCanvasProps extends Omit<CanvasProps, "children" | "style" | "frameloop" | "gl">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {
176 children: ReactNode;
177}
178
179/**
180 * Ready-to-use <Canvas> shared by every background.
181 * - Pauses the render loop while the canvas is scrolled out of view.
182 * - Renders a single still frame when the user prefers reduced motion.
183 * - Caps the pixel ratio; R3F disposes the renderer and releases the WebGL
184 * context (forceContextLoss) when the Canvas unmounts.
185 */
186function BackgroundCanvas({ children, dpr = [1, 1.75], pauseWhenOffscreen = DEFAULT_3D_PROPS.pauseWhenOffscreen, lowPowerMode = DEFAULT_3D_PROPS.lowPowerMode, ...canvasProps }: BackgroundCanvasProps) {
187 const containerRef = useRef<HTMLDivElement>(null);
188 // Starts "in view" so the first frame is always drawn before the loop can be paused
189 const [inView, setInView] = useState(true);
190 const [reducedMotion, setReducedMotion] = useState(false);
191
192 useEffect(() => {
193 const el = containerRef.current;
194 if (!el) return undefined;
195 const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting));
196 observer.observe(el);
197
198 const query = window.matchMedia("(prefers-reduced-motion: reduce)");
199 const sync = () => setReducedMotion(query.matches);
200 sync();
201 query.addEventListener("change", sync);
202
203 return () => {
204 observer.disconnect();
205 query.removeEventListener("change", sync);
206 };
207 }, []);
208
209 return (
210 <div ref={containerRef} style={FILL_STYLE} aria-hidden="true">
211 <Canvas
212 dpr={lowPowerMode ? 1 : dpr}
213 frameloop={!inView && pauseWhenOffscreen ? "never" : reducedMotion ? "demand" : "always"}
214 gl={{ antialias: true, alpha: true, powerPreference: "high-performance" }}
215 style={{ pointerEvents: "none" }}
216 {...canvasProps}
217 >
218 {children}
219 </Canvas>
220 </div>
221 );
222}
223
224export interface StarfieldProps extends Pick<MotionProps, "particleCount">, Pick<MaterialProps, "primaryColor">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {
225 /** Default 3000. */
226 particleCount?: number;
227 /** @deprecated Use `particleCount`. */
228 starCount?: number;
229 primaryColor?: string;
230 /** @deprecated Use `primaryColor`. */
231 starColor?: string;
232 /** Cruise speed multiplier. Default 1. */
233 baseSpeed?: number;
234 /** Length of the streaks: 0 = round stars. Default 1. */
235 stretchFactor?: number;
236 /** Scrolling or using the wheel triggers the hyperspace jump. Default true. */
237 scrollAcceleration?: boolean;
238}
239
240const FIELD_DEPTH = 200;
241const FIELD_RADIUS = 40;
242const MAX_BOOST = 4;
243
244const vertexShader = /* glsl */ `
245uniform float uTravel;
246uniform float uStretch;
247uniform float uSize;
248uniform float uPixelRatio;
249uniform vec2 uResolution;
250
251attribute float aSeed;
252
253varying vec2 vDir;
254varying float vLength;
255varying float vWidth;
256varying float vBright;
257varying float vSeed;
258
259const float DEPTH = ${FIELD_DEPTH.toFixed(1)};
260
261vec2 toScreen(vec4 clip) {
262 return clip.xy / clip.w * 0.5 * uResolution;
263}
264
265void main() {
266 // Each star flies towards the camera at its own pace, then wraps back to the far end
267 float depth = mod(position.z - uTravel * (0.7 + aSeed * 0.6), DEPTH) + 0.3;
268 vec3 head = vec3(position.xy, -depth);
269 // The tail is the same star a little further away: projected, it gives the streak on screen
270 vec3 tail = vec3(position.xy, -depth - uStretch * (0.4 + aSeed * 0.8));
271
272 vec4 clipHead = projectionMatrix * modelViewMatrix * vec4(head, 1.0);
273 vec4 clipTail = projectionMatrix * modelViewMatrix * vec4(tail, 1.0);
274 vec2 streak = toScreen(clipHead) - toScreen(clipTail); // pixels, pointing outwards
275 float len = length(streak);
276
277 float width = uSize * uPixelRatio * (0.6 + aSeed * 0.9) * clamp(40.0 / depth, 0.35, 2.5);
278 // The sprite is centered on the head and must contain the whole tail
279 float size = min(2.0 * len + width * 2.0, 1024.0);
280
281 gl_Position = clipHead;
282 gl_PointSize = size;
283 vDir = len > 0.001 ? streak / len : vec2(0.0, 1.0);
284 vLength = min(len, size * 0.5 - width) / size;
285 vWidth = width / size;
286 // Fade in from the far end, so wrapping stars never pop into view
287 vBright = 1.0 - smoothstep(DEPTH * 0.55, DEPTH, depth);
288 vSeed = aSeed;
289}
290`;
291
292const fragmentShader = /* glsl */ `
293uniform vec3 uColor;
294
295varying vec2 vDir;
296varying float vLength;
297varying float vWidth;
298varying float vBright;
299varying float vSeed;
300
301void main() {
302 // Sprite space with Y up, head at the center, tail towards -vDir
303 vec2 p = gl_PointCoord - 0.5;
304 p.y = -p.y;
305 vec2 tail = -vDir * vLength;
306 float h = clamp(dot(p, tail) / max(dot(tail, tail), 1e-6), 0.0, 1.0);
307 float dist = length(p - tail * h);
308
309 float core = 1.0 - smoothstep(0.0, vWidth * 0.5, dist);
310 float fade = vLength > 0.0001 ? 1.0 - h : 1.0;
311 float alpha = core * fade * vBright;
312 if (alpha < 0.005) discard;
313
314 // Slight hue spread: some stars bluer, some warmer; heads are hot (HDR, bloomed)
315 vec3 tint = mix(uColor, vec3(0.75, 0.85, 1.0), vSeed * 0.5);
316 if (vSeed > 0.92) tint = mix(uColor, vec3(1.0, 0.85, 0.7), 0.6);
317 gl_FragColor = vec4(tint * (1.2 + 2.0 * (1.0 - h)), alpha);
318 #include <colorspace_fragment>
319}
320`;
321
322// Blue glow at the vanishing point during the jump
323const flashFragmentShader = /* glsl */ `
324uniform float uBoost;
325uniform vec3 uColor;
326varying vec2 vUv;
327void main() {
328 float d = length(vUv - 0.5) * 2.0;
329 float glow = exp(-d * d * 14.0) * uBoost * 0.22;
330 gl_FragColor = vec4(mix(uColor, vec3(0.35, 0.55, 1.0), 0.7) * glow, 1.0);
331 #include <colorspace_fragment>
332}
333`;
334
335const flashVertexShader = /* glsl */ `
336varying vec2 vUv;
337void main() {
338 vUv = uv;
339 gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
340}
341`;
342
343interface StarsProps {
344 starCount: number;
345 starColor: string;
346 baseSpeed: number;
347 stretchFactor: number;
348 boost: RefObject<number>;
349 aberration: RefObject<ChromaticAberrationEffect | null>;
350}
351
352const Stars = memo(function Stars({ starCount, starColor, baseSpeed, stretchFactor, boost, aberration }: StarsProps) {
353 const travel = useRef(0);
354 const count = Math.max(1, Math.round(starCount));
355
356 const geometry = useMemo(() => {
357 const positions = new Float32Array(count * 3);
358 const seeds = new Float32Array(count);
359 for (let i = 0; i < count; i++) {
360 // Keep a clear corridor around the axis: nothing streaks straight through the vanishing point
361 const r = 1.5 + Math.sqrt(Math.random()) * (FIELD_RADIUS - 1.5);
362 const a = Math.random() * Math.PI * 2;
363 positions[i * 3] = Math.cos(a) * r;
364 positions[i * 3 + 1] = Math.sin(a) * r;
365 positions[i * 3 + 2] = Math.random() * FIELD_DEPTH;
366 seeds[i] = Math.random();
367 }
368 const g = new THREE.BufferGeometry();
369 g.setAttribute("position", new THREE.BufferAttribute(positions, 3));
370 g.setAttribute("aSeed", new THREE.BufferAttribute(seeds, 1));
371 return g;
372 }, [count]);
373
374 const flashGeometry = useMemo(() => new THREE.PlaneGeometry(160, 160), []);
375
376 const materials = useMemo(() => {
377 const color = new THREE.Color();
378 const stars = new THREE.ShaderMaterial({
379 uniforms: {
380 uTravel: { value: 0 },
381 uStretch: { value: 1 },
382 uSize: { value: 2.2 },
383 uPixelRatio: { value: 1 },
384 uResolution: { value: new THREE.Vector2(1, 1) },
385 uColor: { value: color },
386 },
387 vertexShader,
388 fragmentShader,
389 transparent: true,
390 depthWrite: false,
391 blending: THREE.AdditiveBlending,
392 });
393 const flash = new THREE.ShaderMaterial({
394 uniforms: { uBoost: { value: 0 }, uColor: { value: color } },
395 vertexShader: flashVertexShader,
396 fragmentShader: flashFragmentShader,
397 transparent: true,
398 depthWrite: false,
399 blending: THREE.AdditiveBlending,
400 });
401 return { stars, flash, color };
402 }, []);
403
404 useEffect(() => {
405 materials.color.set(starColor);
406 }, [materials, starColor]);
407
408 useEffect(() => () => geometry.dispose(), [geometry]);
409 useEffect(() => () => flashGeometry.dispose(), [flashGeometry]);
410 useEffect(
411 () => () => {
412 materials.stars.dispose();
413 materials.flash.dispose();
414 },
415 [materials]
416 );
417
418 useFrame((state, delta) => {
419 const dt = Math.min(delta, 1 / 30);
420 boost.current *= Math.exp(-1.2 * dt);
421 const b = boost.current;
422
423 // Cruise, then a dramatic jump: speed and streaks grow much faster than linearly with the boost
424 travel.current += dt * baseSpeed * (9 + b * b * 22);
425 const u = materials.stars.uniforms;
426 u.uTravel.value = travel.current;
427 u.uStretch.value = stretchFactor * baseSpeed * (0.8 + b * b * 14);
428 u.uPixelRatio.value = state.viewport.dpr;
429 state.gl.getDrawingBufferSize(u.uResolution.value as THREE.Vector2);
430 materials.flash.uniforms.uBoost.value = b;
431
432 // Field of view widens during the jump; slow roll the rest of the time
433 const camera = state.camera as THREE.PerspectiveCamera;
434 camera.rotation.z += dt * 0.03;
435 const fov = 60 + b * 7;
436 if (Math.abs(camera.fov - fov) > 0.01) {
437 camera.fov = THREE.MathUtils.damp(camera.fov, fov, 5, dt);
438 camera.updateProjectionMatrix();
439 }
440
441 const effect = aberration.current;
442 if (effect) effect.offset.set(0.0004 + b * 0.0022, 0.0003 + b * 0.0016);
443 });
444
445 return (
446 <>
447 <mesh geometry={flashGeometry} material={materials.flash} position={[0, 0, -120]} />
448 <points geometry={geometry} material={materials.stars} frustumCulled={false} />
449 </>
450 );
451});
452
453function HyperspaceStarfieldBackground({
454 particleCount,
455 starCount = particleCount ?? 3000,
456 primaryColor,
457 starColor = primaryColor ?? "#cfe3ff",
458 baseSpeed = 1,
459 stretchFactor = 1,
460 scrollAcceleration = true,
461 pauseWhenOffscreen,
462 lowPowerMode,
463}: StarfieldProps) {
464 const boost = useRef(0);
465 const aberration = useRef<ChromaticAberrationEffect>(null);
466 const aberrationOffset = useMemo(() => new THREE.Vector2(0.0004, 0.0003), []);
467
468 // Wheel input and page scroll feed the jump; it decays on its own
469 useEffect(() => {
470 if (!scrollAcceleration) return undefined;
471 let lastScrollY = window.scrollY;
472 const add = (amount: number) => {
473 boost.current = Math.min(MAX_BOOST, boost.current + amount);
474 };
475 const onWheel = (event: WheelEvent) => add(Math.abs(event.deltaY) * 0.0012);
476 const onScroll = () => {
477 add(Math.abs(window.scrollY - lastScrollY) * 0.0016);
478 lastScrollY = window.scrollY;
479 };
480 window.addEventListener("wheel", onWheel, { passive: true });
481 window.addEventListener("scroll", onScroll, { passive: true });
482 return () => {
483 window.removeEventListener("wheel", onWheel);
484 window.removeEventListener("scroll", onScroll);
485 };
486 }, [scrollAcceleration]);
487
488 return (
489 <BackgroundCanvas pauseWhenOffscreen={pauseWhenOffscreen} lowPowerMode={lowPowerMode} camera={{ position: [0, 0, 0], fov: 60, near: 0.1, far: FIELD_DEPTH + 20 }}>
490 <color attach="background" args={["#010103"]} />
491 <Stars
492 starCount={starCount}
493 starColor={starColor}
494 baseSpeed={baseSpeed}
495 stretchFactor={stretchFactor}
496 boost={boost}
497 aberration={aberration}
498 />
499 <EffectComposer multisampling={0}>
500 <Bloom mipmapBlur intensity={1.1} luminanceThreshold={0.6} luminanceSmoothing={0.2} />
501 <ChromaticAberration ref={aberration} offset={aberrationOffset} radialModulation modulationOffset={0.2} />
502 <Vignette offset={0.2} darkness={0.85} />
503 </EffectComposer>
504 </BackgroundCanvas>
505 );
506}
507
508export default memo(HyperspaceStarfieldBackground);
03

Drop it in a page

Updated live with the settings above.

app/page.tsx
1import HyperspaceStarfieldBackground from "@/components/HyperspaceStarfieldBackground";
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 <HyperspaceStarfieldBackground
8 particleCount={3000}
9 baseSpeed={1}
10 stretchFactor={1}
11 primaryColor="#cfe3ff"
12 />
13 </div>
14 );
15}
Next componentIridescent Silk→