Loading…
← All components

Background · Lines

Topographic Lines

Glowing ridge lines rolling like a contour map; the cursor leaves shock waves across them.

<TopographicLinesBackground />Live

Customize

Lines#e2e8f0

Installation

Use it in your project

Or skip the copy-paste

One command: writes the file and installs the dependencies.

$ npx deepui-cli add topographic-lines
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/TopographicLinesBackground.tsx and paste it in.

components/TopographicLinesBackground.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 { LineSegments2 } from "three/examples/jsm/lines/LineSegments2.js";
15import { LineSegmentsGeometry } from "three/examples/jsm/lines/LineSegmentsGeometry.js";
16import { LineMaterial } from "three/examples/jsm/lines/LineMaterial.js";
17import { SimplexNoise } from "three/examples/jsm/math/SimplexNoise.js";
18import { Canvas, useFrame, useThree, type CanvasProps } from "@react-three/fiber";
19import { Bloom, EffectComposer, Vignette } from "@react-three/postprocessing";
20
21/**
22 * The shared props API of DeepUI's individual 3D components (not the full-page templates, which keep
23 * their own tailored scenes).
24 *
25 * The props are grouped by concern. A component extends ONLY the groups it really applies, so its
26 * 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 are
32 * inlined into each component's single-file bundle (lib/bundle-source.mjs), only what it uses.
33 */
34
35/** 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";
37
38/** 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}
49
50/** 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}
61
62/** 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}
75
76/** 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}
93
94/** 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}
105
106/** 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}
115
116/** 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}
125
126/** Every group at once. Components extend only the groups they apply (see the top of this file). */
127interface Base3DComponentProps
128 extends CursorProps,
129 TiltProps,
130 Text3DProps,
131 MaterialProps,
132 MotionProps,
133 EnvironmentProps,
134 PerformanceProps {}
135
136type Defaults = Required<Omit<Base3DComponentProps, "text" | "fontUrl" | "particleCount" | "cameraFov">>;
137
138/** 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};
167
168/** 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};
177
178interface BackgroundCanvasProps extends Omit<CanvasProps, "children" | "style" | "frameloop" | "gl">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {
179 children: ReactNode;
180}
181
182/**
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 WebGL
187 * 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 paused
192 const [inView, setInView] = useState(true);
193 const [reducedMotion, setReducedMotion] = useState(false);
194
195 useEffect(() => {
196 const el = containerRef.current;
197 if (!el) return undefined;
198 const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting));
199 observer.observe(el);
200
201 const query = window.matchMedia("(prefers-reduced-motion: reduce)");
202 const sync = () => setReducedMotion(query.matches);
203 sync();
204 query.addEventListener("change", sync);
205
206 return () => {
207 observer.disconnect();
208 query.removeEventListener("change", sync);
209 };
210 }, []);
211
212 return (
213 <div ref={containerRef} style={FILL_STYLE} aria-hidden="true">
214 <Canvas
215 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}
226
227interface 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}
235
236/**
237 * Tracks the pointer relative to the canvas through window listeners: the
238 * 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);
245
246 useEffect(() => {
247 onDownRef.current = onDown;
248 }, [onDown]);
249
250 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 };
270
271 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]);
284
285 return pointer;
286}
287
288export interface TopographicLinesProps extends Pick<MaterialProps, "primaryColor">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {
289 /** Number of ridge lines, front to back. Default 40. */
290 lineCount?: number;
291 primaryColor?: string;
292 /** @deprecated Use `primaryColor`. */
293 lineColor?: string;
294 /** Line thickness in CSS pixels. Default 1.5. */
295 lineWidth?: number;
296 /** Frequency of the relief: higher = more, narrower peaks. Default 0.18. */
297 noiseScale?: number;
298 speed?: number;
299 /** Strength of the shock waves left by the cursor. 0 disables them. Default 1. */
300 mouseInfluence?: number;
301}
302
303const BACKGROUND = "#050506";
304const POINTS_PER_LINE = 160;
305const WIDTH = 26;
306const DEPTH = 22;
307const MAX_IMPACTS = 8;
308const RIPPLE_SPEED = 4.5; // world units per second
309
310interface Impact {
311 x: number;
312 z: number;
313 time: number;
314}
315
316const TopographicLines = memo(function TopographicLines({
317 lineCount,
318 lineColor,
319 lineWidth,
320 noiseScale,
321 speed,
322 mouseInfluence,
323}: Required<Omit<TopographicLinesProps, "primaryColor" | "pauseWhenOffscreen" | "lowPowerMode">>) {
324 const pointer = useCanvasPointer();
325 const noise = useMemo(() => new SimplexNoise(), []);
326 const impacts = useRef<Impact[]>([]);
327 const lastImpact = useRef({ x: Infinity, z: Infinity, time: -Infinity });
328 const color = useMemo(() => new THREE.Color(), []);
329 const scratch = useMemo(
330 () => ({ raycaster: new THREE.Raycaster(), plane: new THREE.Plane(new THREE.Vector3(0, 1, 0), 0), hit: new THREE.Vector3() }),
331 []
332 );
333
334 const rows = Math.max(2, Math.round(lineCount));
335 const segmentsPerLine = POINTS_PER_LINE - 1;
336
337 // Ridge lines: fat lines (LineSegments2) whose vertices are rewritten every frame
338 const lineGeometry = useMemo(() => {
339 const g = new LineSegmentsGeometry();
340 const floats = rows * segmentsPerLine * 6;
341 g.setPositions(new Float32Array(floats));
342 g.setColors(new Float32Array(floats));
343 return g;
344 }, [rows, segmentsPerLine]);
345
346 // Occluders: a strip under each line, in the background color. Peaks in front hide the lines behind
347 // them, which is what gives the "Unknown Pleasures" ridge look instead of a tangle of wires.
348 const occluderGeometry = useMemo(() => {
349 const g = new THREE.BufferGeometry();
350 g.setAttribute("position", new THREE.BufferAttribute(new Float32Array(rows * POINTS_PER_LINE * 2 * 3), 3).setUsage(THREE.DynamicDrawUsage));
351 const indices: number[] = [];
352 for (let r = 0; r < rows; r++) {
353 const base = r * POINTS_PER_LINE * 2;
354 for (let k = 0; k < segmentsPerLine; k++) {
355 const a = base + k * 2;
356 indices.push(a, a + 1, a + 2, a + 1, a + 3, a + 2);
357 }
358 }
359 g.setIndex(indices);
360 return g;
361 }, [rows, segmentsPerLine]);
362
363 const lineMaterial = useMemo(() => {
364 const m = new LineMaterial({ color: 0xffffff, linewidth: 1.5, vertexColors: true, worldUnits: false });
365 m.fog = true;
366 return m;
367 }, []);
368 const occluderMaterial = useMemo(
369 () =>
370 new THREE.MeshBasicMaterial({
371 color: BACKGROUND,
372 side: THREE.DoubleSide,
373 // Pushed back a little so the line drawn on its top edge is never hidden by its own strip
374 polygonOffset: true,
375 polygonOffsetFactor: 1,
376 polygonOffsetUnits: 1,
377 }),
378 []
379 );
380
381 const lines = useMemo(() => {
382 const l = new LineSegments2(lineGeometry, lineMaterial);
383 l.frustumCulled = false;
384 return l;
385 }, [lineGeometry, lineMaterial]);
386
387 useEffect(() => {
388 lineMaterial.linewidth = lineWidth;
389 color.set(lineColor);
390 }, [lineMaterial, lineWidth, lineColor, color]);
391
392 useEffect(
393 () => () => {
394 lineGeometry.dispose();
395 occluderGeometry.dispose();
396 },
397 [lineGeometry, occluderGeometry]
398 );
399 useEffect(
400 () => () => {
401 lineMaterial.dispose();
402 occluderMaterial.dispose();
403 },
404 [lineMaterial, occluderMaterial]
405 );
406
407 useFrame((state) => {
408 const time = state.clock.elapsedTime;
409 const t = time * speed * 0.25;
410 lineMaterial.resolution.set(state.size.width, state.size.height);
411
412 // Cursor → point on the ground plane; a new impact is dropped every time it travels far enough
413 const p = pointer.current;
414 if (p.inside && mouseInfluence > 0) {
415 scratch.raycaster.setFromCamera(p.ndc, state.camera);
416 if (scratch.raycaster.ray.intersectPlane(scratch.plane, scratch.hit)) {
417 const last = lastImpact.current;
418 const moved = Math.hypot(scratch.hit.x - last.x, scratch.hit.z - last.z);
419 if (moved > 0.9 && time - last.time > 0.12) {
420 lastImpact.current = { x: scratch.hit.x, z: scratch.hit.z, time };
421 impacts.current.push({ x: scratch.hit.x, z: scratch.hit.z, time });
422 if (impacts.current.length > MAX_IMPACTS) impacts.current.shift();
423 }
424 }
425 }
426 const live = impacts.current.filter((impact) => time - impact.time < 3.5);
427 impacts.current = live;
428
429 const positions = (lineGeometry.attributes.instanceStart as THREE.InterleavedBufferAttribute).data;
430 const colors = (lineGeometry.attributes.instanceColorStart as THREE.InterleavedBufferAttribute).data;
431 const occluder = occluderGeometry.attributes.position as THREE.BufferAttribute;
432 const pos = positions.array as Float32Array;
433 const col = colors.array as Float32Array;
434 const occ = occluder.array as Float32Array;
435 const sigma = WIDTH * 0.17;
436
437 let prevX = 0;
438 let prevY = 0;
439 let prevB = 0;
440 for (let r = 0; r < rows; r++) {
441 const z = -DEPTH / 2 + (r / (rows - 1)) * DEPTH;
442 for (let k = 0; k < POINTS_PER_LINE; k++) {
443 const x = -WIDTH / 2 + (k / (POINTS_PER_LINE - 1)) * WIDTH;
444
445 // Relief: a mountain range concentrated in the middle (gaussian envelope), flat noise on the sides
446 const envelope = Math.exp(-(x * x) / (2 * sigma * sigma));
447 const n = noise.noise3d(x * noiseScale, z * noiseScale * 1.6, t) * 0.5 + 0.5;
448 const detail = noise.noise3d(x * noiseScale * 3.1, z * noiseScale * 3.1, t * 1.7);
449 let y = envelope * n * n * 3.2 + detail * 0.12 * (0.3 + envelope);
450
451 // Shock waves: damped rings spreading from every impact
452 let wave = 0;
453 for (let i = 0; i < live.length; i++) {
454 const impact = live[i];
455 const age = time - impact.time;
456 const d = Math.hypot(x - impact.x, z - impact.z);
457 const front = 1 - THREE.MathUtils.smoothstep(d, age * RIPPLE_SPEED - 0.6, age * RIPPLE_SPEED + 0.6);
458 wave += Math.sin(d * 2.6 - age * 9) * Math.exp(-age * 1.1) * Math.exp(-d * 0.18) * front;
459 }
460 y += wave * 0.9 * mouseInfluence;
461
462 // Peaks and wave crests glow (HDR > 1, picked up by the bloom)
463 const brightness = 0.32 + Math.min(Math.max(y, 0) / 3, 1) * 1.3 + Math.abs(wave) * 0.9 * mouseInfluence;
464
465 const o = (r * POINTS_PER_LINE + k) * 6;
466 occ[o] = x;
467 occ[o + 1] = y;
468 occ[o + 2] = z;
469 occ[o + 3] = x;
470 occ[o + 4] = -2;
471 occ[o + 5] = z;
472
473 if (k > 0) {
474 const s = (r * segmentsPerLine + k - 1) * 6;
475 pos[s] = prevX;
476 pos[s + 1] = prevY;
477 pos[s + 2] = z;
478 pos[s + 3] = x;
479 pos[s + 4] = y;
480 pos[s + 5] = z;
481 col[s] = color.r * prevB;
482 col[s + 1] = color.g * prevB;
483 col[s + 2] = color.b * prevB;
484 col[s + 3] = color.r * brightness;
485 col[s + 4] = color.g * brightness;
486 col[s + 5] = color.b * brightness;
487 }
488 prevX = x;
489 prevY = y;
490 prevB = brightness;
491 }
492 }
493 positions.needsUpdate = true;
494 colors.needsUpdate = true;
495 occluder.needsUpdate = true;
496 });
497
498 return (
499 <>
500 <primitive object={lines} />
501 <mesh geometry={occluderGeometry} material={occluderMaterial} frustumCulled={false} />
502 </>
503 );
504});
505
506function TopographicLinesBackground({
507 lineCount = 40,
508 primaryColor,
509 lineColor = primaryColor ?? "#e2e8f0",
510 lineWidth = 1.5,
511 noiseScale = 0.18,
512 speed = 1,
513 mouseInfluence = 1,
514 pauseWhenOffscreen,
515 lowPowerMode,
516}: TopographicLinesProps) {
517 return (
518 <BackgroundCanvas pauseWhenOffscreen={pauseWhenOffscreen} lowPowerMode={lowPowerMode} camera={{ position: [0, 7, 15], fov: 38 }} onCreated={({ camera }) => camera.lookAt(0, 0.4, -1)}>
519 <color attach="background" args={[BACKGROUND]} />
520 <fog attach="fog" args={[BACKGROUND, 14, 34]} />
521 <TopographicLines
522 lineCount={lineCount}
523 lineColor={lineColor}
524 lineWidth={lineWidth}
525 noiseScale={noiseScale}
526 speed={speed}
527 mouseInfluence={mouseInfluence}
528 />
529 <EffectComposer multisampling={0}>
530 <Bloom mipmapBlur intensity={0.9} luminanceThreshold={0.7} luminanceSmoothing={0.2} />
531 <Vignette offset={0.25} darkness={0.8} />
532 </EffectComposer>
533 </BackgroundCanvas>
534 );
535}
536
537export default memo(TopographicLinesBackground);
03

Drop it in a page

Updated live with the settings above.

app/page.tsx
1import TopographicLinesBackground from "@/components/TopographicLinesBackground";
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 <TopographicLinesBackground
8 lineCount={40}
9 lineWidth={1.5}
10 noiseScale={0.18}
11 speed={1}
12 mouseInfluence={1}
13 primaryColor="#e2e8f0"
14 />
15 </div>
16 );
17}
Next componentGrid Matrix→