← All components Next componentVolumetric Aura→
Background · Grid
Grid Matrix
A field of modules that rise, turn and glow around the cursor, with a ghost cursor when there is none.
<InteractiveGridMatrixBackground />Live
Move your cursor over the grid
Customize
Base#1e293b
Active#38bdf8
Installation
Use it in your project
Or skip the copy-paste
One command: writes the file and installs the dependencies.
$ npx deepui-cli add grid-matrix
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/InteractiveGridMatrixBackground.tsx and paste it in.
components/InteractiveGridMatrixBackground.tsx
1"use client";23import {4 memo,5 useEffect,6 useLayoutEffect,7 useMemo,8 useRef,9 useState,10 type CSSProperties,11 type ReactNode,12 type RefObject,13} from "react";14import * as THREE from "three";15import { RoundedBoxGeometry } from "three/examples/jsm/geometries/RoundedBoxGeometry.js";16import { Canvas, useFrame, useThree, type CanvasProps } from "@react-three/fiber";17import { Environment, Lightformer } from "@react-three/drei";18import { Bloom, EffectComposer, Vignette } from "@react-three/postprocessing";1920/**21 * The shared props API of DeepUI's individual 3D components (not the full-page templates, which keep22 * their own tailored scenes).23 *24 * The props are grouped by concern. A component extends ONLY the groups it really applies, so its25 * type never advertises a knob that does nothing (a card has no particles, a background has no tilt):26 *27 * interface MyCardProps extends CursorProps, TiltProps, MaterialProps, PerformanceProps { … }28 *29 * `Base3DComponentProps` is every group at once, for tooling that handles any component. Same name,30 * same unit and same meaning everywhere; the default values live in DEFAULT_3D_PROPS. These files are31 * inlined into each component's single-file bundle (lib/bundle-source.mjs), only what it uses.32 */3334/** Which rotation axes follow the pointer. "x-only": the object nods (up / down); "y-only": it turns (left / right). */35export type TiltAxis = "both" | "x-only" | "y-only" | "none";3637/** 1. Cursor: how the pointer pulls, pushes and drags the object. */38interface CursorProps {39 /** 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). */40 cursorRadius?: number;41 /** Positive pulls things towards the pointer, negative pushes them away (repulsion, shockwave). Default 1. */42 cursorForce?: number;43 /** How far the object slides towards the pointer, 0 (stays put) to 1 (follows closely). Default 0. */44 magneticStrength?: number;45 /** Share of the remaining distance the motion closes each frame (at 60 fps), 0.01 (heavy, slow) to 1 (instant). Default 0.1. */46 cursorDamping?: number;47}4849/** 2. Tilt and parallax: the object leans towards the pointer, its layers slide against each other. */50interface TiltProps {51 /** Largest lean towards the pointer, in degrees. Default 15. */52 maxTiltAngle?: number;53 /** Axes that follow the pointer. Default "both". */54 tiltAxis?: TiltAxis;55 /** Lean away from the pointer instead of towards it. Default false. */56 invertTilt?: boolean;57 /** How far apart the depth layers slide when the object tilts, 0 (flat) to 2. Default 1. */58 parallaxOffset?: number;59}6061/** 3. Text and 3D typography, for components that draw a label. */62interface Text3DProps {63 /** The label drawn by the component. */64 text?: string;65 /** Scale of the lettering. Default 1. */66 fontSize?: number;67 /** Extrusion depth of 3D letters. Default 0.2. */68 textDepth?: number;69 /** Bevelled, light-catching edges on 3D letters. Default true. */70 bevelEnabled?: boolean;71 /** Custom font: a .woff / .ttf (flat text) or a typeface .json (extruded text). */72 fontUrl?: string;73}7475/** 4. Rendering, materials and glow. */76interface MaterialProps {77 /** Main color of the object. Default "#6366f1". */78 primaryColor?: string;79 /** Color of the glow. Default "#00f0ff". */80 emissiveColor?: string;81 /** Strength of the glow, 0 (none) to 3. Default 1. */82 emissiveIntensity?: number;83 /** 0 (mirror, glass) to 1 (matte). Default 0.3. */84 roughness?: number;85 /** 0 (plastic, organic) to 1 (metal). Default 0.5. */86 metalness?: number;87 /** 0 (opaque) to 1 (clear glass): see-through, refracting surfaces. Default 0. */88 transmission?: number;89 /** Technical wireframe rendering. Default false. */90 wireframe?: boolean;91}9293/** 5. Particles, idle motion and shader animation. */94interface MotionProps {95 /** Number of instanced elements. Default depends on the component. */96 particleCount?: number;97 /** Spin on its own, in radians per second (negative: the other way; 0.5 ≈ one turn in 12 s). Default 0. */98 autoRotateSpeed?: number;99 /** Pulses or ripples per second. Default 1. */100 pulseRate?: number;101 /** Amplitude of the noise deformation, 0 (none) to 2. Default 1. */102 displacementScale?: number;103}104105/** 6. Environment and camera. */106interface EnvironmentProps {107 /** Camera field of view, in degrees. Default depends on the component. */108 cameraFov?: number;109 /** Color of the depth fog. Default "#0a0a0a". */110 fogColor?: string;111 /** Thickness of the fog, 0 (none) to 0.2. Default 0. */112 fogDensity?: number;113}114115/** 7. Performance and accessibility. */116interface PerformanceProps {117 /** Lighter rendering for weak devices: pixel ratio 1, fewer instances, smaller environment maps. Default false. */118 lowPowerMode?: boolean;119 /** Under the OS "reduce motion" setting, stop idle spin, pulses and deformation (pointer feedback stays). Default true. */120 respectReducedMotion?: boolean;121 /** Stop the render loop while the component is scrolled out of view. Default true. */122 pauseWhenOffscreen?: boolean;123}124125/** Every group at once. Components extend only the groups they apply (see the top of this file). */126interface Base3DComponentProps127 extends CursorProps,128 TiltProps,129 Text3DProps,130 MaterialProps,131 MotionProps,132 EnvironmentProps,133 PerformanceProps {}134135type Defaults = Required<Omit<Base3DComponentProps, "text" | "fontUrl" | "particleCount" | "cameraFov">>;136137/** The values a prop takes when it is left out. A component may override one, and then documents it. */138const DEFAULT_3D_PROPS: Defaults = {139 cursorRadius: 220,140 cursorForce: 1,141 magneticStrength: 0,142 cursorDamping: 0.1,143 maxTiltAngle: 15,144 tiltAxis: "both",145 invertTilt: false,146 parallaxOffset: 1,147 fontSize: 1,148 textDepth: 0.2,149 bevelEnabled: true,150 primaryColor: "#6366f1",151 emissiveColor: "#00f0ff",152 emissiveIntensity: 1,153 roughness: 0.3,154 metalness: 0.5,155 transmission: 0,156 wireframe: false,157 autoRotateSpeed: 0,158 pulseRate: 1,159 displacementScale: 1,160 fogColor: "#0a0a0a",161 fogDensity: 0,162 lowPowerMode: false,163 respectReducedMotion: true,164 pauseWhenOffscreen: true,165};166167/** Fills the positioned parent; never intercepts clicks meant for the page content above it. */168const FILL_STYLE: CSSProperties = {169 position: "absolute",170 top: 0,171 left: 0,172 width: "100%",173 height: "100%",174 pointerEvents: "none",175};176177interface BackgroundCanvasProps extends Omit<CanvasProps, "children" | "style" | "frameloop" | "gl">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {178 children: ReactNode;179}180181/**182 * Ready-to-use <Canvas> shared by every background.183 * - Pauses the render loop while the canvas is scrolled out of view.184 * - Renders a single still frame when the user prefers reduced motion.185 * - Caps the pixel ratio; R3F disposes the renderer and releases the WebGL186 * context (forceContextLoss) when the Canvas unmounts.187 */188function BackgroundCanvas({ children, dpr = [1, 1.75], pauseWhenOffscreen = DEFAULT_3D_PROPS.pauseWhenOffscreen, lowPowerMode = DEFAULT_3D_PROPS.lowPowerMode, ...canvasProps }: BackgroundCanvasProps) {189 const containerRef = useRef<HTMLDivElement>(null);190 // Starts "in view" so the first frame is always drawn before the loop can be paused191 const [inView, setInView] = useState(true);192 const [reducedMotion, setReducedMotion] = useState(false);193194 useEffect(() => {195 const el = containerRef.current;196 if (!el) return undefined;197 const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting));198 observer.observe(el);199200 const query = window.matchMedia("(prefers-reduced-motion: reduce)");201 const sync = () => setReducedMotion(query.matches);202 sync();203 query.addEventListener("change", sync);204205 return () => {206 observer.disconnect();207 query.removeEventListener("change", sync);208 };209 }, []);210211 return (212 <div ref={containerRef} style={FILL_STYLE} aria-hidden="true">213 <Canvas214 dpr={lowPowerMode ? 1 : dpr}215 frameloop={!inView && pauseWhenOffscreen ? "never" : reducedMotion ? "demand" : "always"}216 gl={{ antialias: true, alpha: true, powerPreference: "high-performance" }}217 style={{ pointerEvents: "none" }}218 {...canvasProps}219 >220 {children}221 </Canvas>222 </div>223 );224}225226interface CanvasPointer {227 /** Pointer position in normalized device coordinates of the canvas (-1..1). */228 ndc: THREE.Vector2;229 /** True while the pointer is over the canvas area. */230 inside: boolean;231 /** True while a button is held down. */232 pressed: boolean;233}234235/**236 * Tracks the pointer relative to the canvas through window listeners: the237 * canvas itself has `pointer-events: none`, so R3F's own events never fire.238 * Returns a ref read inside useFrame — pointer moves never re-render React.239 */240function useCanvasPointer(onDown?: (ndc: THREE.Vector2) => void): RefObject<CanvasPointer> {241 const gl = useThree((state) => state.gl);242 const pointer = useRef<CanvasPointer>({ ndc: new THREE.Vector2(), inside: false, pressed: false });243 const onDownRef = useRef(onDown);244245 useEffect(() => {246 onDownRef.current = onDown;247 }, [onDown]);248249 useEffect(() => {250 const el = gl.domElement;251 const update = (event: PointerEvent) => {252 const rect = el.getBoundingClientRect();253 const p = pointer.current;254 p.ndc.set(((event.clientX - rect.left) / rect.width) * 2 - 1, -((event.clientY - rect.top) / rect.height) * 2 + 1);255 p.inside = Math.abs(p.ndc.x) <= 1 && Math.abs(p.ndc.y) <= 1;256 };257 const down = (event: PointerEvent) => {258 update(event);259 pointer.current.pressed = true;260 if (pointer.current.inside) onDownRef.current?.(pointer.current.ndc);261 };262 const up = () => {263 pointer.current.pressed = false;264 };265 const leave = () => {266 pointer.current.inside = false;267 pointer.current.pressed = false;268 };269270 window.addEventListener("pointermove", update, { passive: true });271 window.addEventListener("pointerdown", down, { passive: true });272 window.addEventListener("pointerup", up, { passive: true });273 document.documentElement.addEventListener("pointerleave", leave);274 window.addEventListener("blur", leave);275 return () => {276 window.removeEventListener("pointermove", update);277 window.removeEventListener("pointerdown", down);278 window.removeEventListener("pointerup", up);279 document.documentElement.removeEventListener("pointerleave", leave);280 window.removeEventListener("blur", leave);281 };282 }, [gl]);283284 return pointer;285}286287/**288 * `cursorDamping` (share of the gap closed per 60 fps frame) as a rate for THREE.MathUtils.damp, so the289 * motion feels the same at 30, 60 or 120 fps.290 */291function dampingToLambda(damping: number): number {292 const share = THREE.MathUtils.clamp(damping, 0.001, 0.999);293 return -Math.log(1 - share) * 60;294}295296export interface GridMatrixProps extends Pick<MaterialProps, "primaryColor" | "emissiveColor">, Pick<CursorProps, "cursorRadius" | "cursorDamping">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {297 /** Default 30. */298 columns?: number;299 /** Default 30. */300 rows?: number;301 primaryColor?: string;302 /** @deprecated Use `primaryColor`. */303 baseColor?: string;304 /** Color the modules light up with near the cursor. */305 emissiveColor?: string;306 /** @deprecated Use `emissiveColor`. */307 activeColor?: string;308 /** Height reached by the module right under the cursor. Default 3. */309 maxElevation?: number;310 /** Radius of the cursor's influence, in modules. Default 4.5. */311 cursorRadius?: number;312 /** @deprecated Use `cursorRadius`. */313 radius?: number;314 cursorDamping?: number;315 /** @deprecated Use `cursorDamping` (shared unit). */316 damping?: number;317}318319const SPACING = 1.1;320// Modules within this many rows of the border shrink and darken away: the grid has no visible edge321const EDGE_FADE = 6;322323const GridMatrix = memo(function GridMatrix({324 columns,325 rows,326 baseColor,327 activeColor,328 maxElevation,329 radius,330 damping,331}: Required<Omit<GridMatrixProps, "primaryColor" | "emissiveColor" | "cursorRadius" | "cursorDamping" | "pauseWhenOffscreen" | "lowPowerMode">>) {332 const meshRef = useRef<THREE.InstancedMesh>(null);333 const pointer = useCanvasPointer();334 const cols = Math.max(1, Math.round(columns));335 const rws = Math.max(1, Math.round(rows));336 const count = cols * rws;337338 const geometry = useMemo(() => {339 // Origin at the base: scaling Y raises the module instead of growing it both ways340 const g = new RoundedBoxGeometry(0.92, 1, 0.92, 2, 0.06);341 g.translate(0, 0.5, 0);342 return g;343 }, []);344 const material = useMemo(() => {345 const m = new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 0.4, metalness: 0.35 });346 // Instance colors above 1 become emissive: active modules light up from inside instead of only reflecting347 m.onBeforeCompile = (shader) => {348 shader.fragmentShader = shader.fragmentShader.replace(349 "#include <emissivemap_fragment>",350 "#include <emissivemap_fragment>\n#ifdef USE_COLOR\n totalEmissiveRadiance += max(vColor.rgb - 1.0, 0.0) * 1.6;\n#endif"351 );352 };353 return m;354 }, []);355356 // Per-module state: grid position, smoothed elevation and activation357 const state = useMemo(() => {358 const gx = new Float32Array(count);359 const gz = new Float32Array(count);360 const fade = new Float32Array(count);361 for (let i = 0; i < count; i++) {362 const c = i % cols;363 const r = Math.floor(i / cols);364 gx[i] = (c - (cols - 1) / 2) * SPACING;365 gz[i] = (r - (rws - 1) / 2) * SPACING;366 const f = Math.min(1, Math.min(c, cols - 1 - c, r, rws - 1 - r) / EDGE_FADE);367 fade[i] = f * f * (3 - 2 * f);368 }369 return { gx, gz, fade, elevation: new Float32Array(count), activation: new Float32Array(count) };370 }, [count, cols, rws]);371372 const scratch = useMemo(373 () => ({374 matrix: new THREE.Matrix4(),375 position: new THREE.Vector3(),376 quaternion: new THREE.Quaternion(),377 scale: new THREE.Vector3(),378 up: new THREE.Vector3(0, 1, 0),379 base: new THREE.Color(),380 active: new THREE.Color(),381 mixed: new THREE.Color(),382 raycaster: new THREE.Raycaster(),383 plane: new THREE.Plane(new THREE.Vector3(0, 1, 0), 0),384 hit: new THREE.Vector3(),385 cursor: new THREE.Vector2(1e6, 1e6),386 }),387 []388 );389390 useEffect(() => {391 scratch.base.set(baseColor);392 scratch.active.set(activeColor);393 }, [scratch, baseColor, activeColor]);394395 useLayoutEffect(() => {396 const mesh = meshRef.current;397 if (!mesh) return;398 mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);399 // Allocates the color buffer once; it is rewritten every frame400 for (let i = 0; i < count; i++) mesh.setColorAt(i, scratch.base);401 mesh.instanceColor?.setUsage(THREE.DynamicDrawUsage);402 }, [count, scratch]);403404 useEffect(() => () => geometry.dispose(), [geometry]);405 useEffect(() => () => material.dispose(), [material]);406 useEffect(() => {407 const mesh = meshRef.current;408 return () => mesh?.dispose();409 }, [count]);410411 useFrame((frame, delta) => {412 const mesh = meshRef.current;413 if (!mesh) return;414 const dt = Math.min(delta, 1 / 30);415 const t = frame.clock.elapsedTime;416 const k = 1 - Math.exp(-damping * dt);417 const { gx, gz, fade, elevation, activation } = state;418 const { matrix, position, quaternion, scale, up, base, active, mixed, raycaster, plane, hit, cursor } = scratch;419420 // Cursor → point on the grid plane (it eases there, so fast moves leave a smooth trail).421 // Without a cursor, a ghost cursor wanders across the grid so the background is never static.422 const p = pointer.current;423 let hasTarget = false;424 if (p.inside) {425 raycaster.setFromCamera(p.ndc, frame.camera);426 hasTarget = raycaster.ray.intersectPlane(plane, hit) !== null;427 }428 if (!hasTarget) {429 hit.set(Math.sin(t * 0.37) * (cols * SPACING * 0.3), 0, Math.sin(t * 0.53 + 1.3) * (rws * SPACING * 0.3));430 }431 if (cursor.x > 1e5) cursor.set(hit.x, hit.z);432 const follow = Math.min(1, dt * (hasTarget ? 14 : 3));433 cursor.x += (hit.x - cursor.x) * follow;434 cursor.y += (hit.z - cursor.y) * follow;435 const hasCursor = true;436 const reach = radius * SPACING;437438 for (let i = 0; i < count; i++) {439 const x = gx[i];440 const z = gz[i];441442 let influence = 0;443 if (hasCursor) {444 const d = Math.hypot(x - cursor.x, z - cursor.y);445 const f = Math.max(0, 1 - d / reach);446 influence = f * f * (3 - 2 * f); // smoothstep falloff447 }448 // Idle swell so the matrix breathes even without a cursor449 const idle = (Math.sin(x * 0.35 + t * 1.2) * Math.cos(z * 0.3 + t * 0.9) * 0.5 + 0.5) * 0.45;450451 const edge = fade[i];452 activation[i] += (influence * edge - activation[i]) * k;453 elevation[i] += ((idle + influence * maxElevation) * edge - elevation[i]) * k;454 const a = activation[i];455456 position.set(x, 0, z);457 quaternion.setFromAxisAngle(up, a * Math.PI * 0.5);458 const footprint = (1 - a * 0.22) * edge;459 scale.set(footprint, Math.max((0.12 + elevation[i]) * edge, 1e-3), footprint);460 mesh.setMatrixAt(i, matrix.compose(position, quaternion, scale));461462 // Base color, slightly lit by height; active modules glow (HDR > 1 for the bloom)463 mixed.copy(base).multiplyScalar(0.7 + Math.min(elevation[i], 1) * 0.5).lerp(active, a);464 mixed.multiplyScalar((1 + a * 1.8) * edge);465 mesh.setColorAt(i, mixed);466 }467 mesh.instanceMatrix.needsUpdate = true;468 if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;469 });470471 return <instancedMesh key={count} ref={meshRef} args={[geometry, material, count]} frustumCulled={false} />;472});473474function InteractiveGridMatrixBackground({475 columns = 30,476 rows = 30,477 primaryColor,478 baseColor = primaryColor ?? "#1e293b",479 emissiveColor,480 activeColor = emissiveColor ?? "#38bdf8",481 maxElevation = 3,482 cursorRadius,483 radius = cursorRadius ?? 4.5,484 cursorDamping,485 damping = cursorDamping !== undefined ? dampingToLambda(cursorDamping) : 6,486 pauseWhenOffscreen,487 lowPowerMode,488}: GridMatrixProps) {489 // Camera distance follows the grid size, from a three-quarter view close enough that the grid runs past490 // the frame; its far side melts into the fog, and its border fades out anyway (EDGE_FADE)491 const span = Math.max(columns, rows) * SPACING;492 return (493 <BackgroundCanvas494 pauseWhenOffscreen={pauseWhenOffscreen}495 lowPowerMode={lowPowerMode}496 camera={{ position: [span * 0.24, span * 0.24, span * 0.34], fov: 42, near: 0.1, far: span * 4 }}497 onCreated={({ camera }) => camera.lookAt(0, 0, 0)}498 >499 <color attach="background" args={["#030407"]} />500 <fog attach="fog" args={["#030407", span * 0.3, span * 0.85]} />501 <ambientLight intensity={0.25} />502 <directionalLight position={[8, 14, 6]} intensity={2} />503 <Environment resolution={128} frames={1}>504 <Lightformer form="rect" intensity={2} position={[0, 10, 0]} rotation-x={Math.PI / 2} scale={[20, 20, 1]} />505 <Lightformer form="rect" intensity={3} color={activeColor} position={[-10, 2, 0]} rotation-y={Math.PI / 2} scale={[20, 2, 1]} />506 <Lightformer form="rect" intensity={1.5} position={[10, 2, 4]} rotation-y={-Math.PI / 2} scale={[20, 2, 1]} />507 </Environment>508 <GridMatrix509 columns={columns}510 rows={rows}511 baseColor={baseColor}512 activeColor={activeColor}513 maxElevation={maxElevation}514 radius={radius}515 damping={damping}516 />517 <EffectComposer multisampling={4}>518 <Bloom mipmapBlur intensity={1.1} luminanceThreshold={0.75} luminanceSmoothing={0.25} />519 <Vignette offset={0.3} darkness={0.8} />520 </EffectComposer>521 </BackgroundCanvas>522 );523}524525export default memo(InteractiveGridMatrixBackground);
03
Drop it in a page
Updated live with the settings above.
app/page.tsx
1import InteractiveGridMatrixBackground from "@/components/InteractiveGridMatrixBackground";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 <InteractiveGridMatrixBackground8 columns={30}9 rows={30}10 maxElevation={3}11 cursorRadius={4.5}12 cursorDamping={0.1}13 primaryColor="#1e293b"14 emissiveColor="#38bdf8"15 />16 </div>17 );18}