← All components Next componentProcedural Terrain→
Background · Particles
Particle Field
Thousands of GPU particles drifting on a noise flow and parting around the cursor.
<ParticleFieldBackground />Live
Move your cursor over it
Customize
Color 1#7dd3fc
Color 2#c084fc
Installation
Use it in your project
Or skip the copy-paste
One command: writes the file and installs the dependencies.
$ npx deepui-cli add particle-field
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/ParticleFieldBackground.tsx and paste it in.
components/ParticleFieldBackground.tsx
1"use client";23import {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, useThree, type CanvasProps } from "@react-three/fiber";15import { shaderMaterial } from "@react-three/drei";16import { Bloom, EffectComposer } from "@react-three/postprocessing";1718/**19 * The shared props API of DeepUI's individual 3D components (not the full-page templates, which keep20 * their own tailored scenes).21 *22 * The props are grouped by concern. A component extends ONLY the groups it really applies, so its23 * 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 are29 * inlined into each component's single-file bundle (lib/bundle-source.mjs), only what it uses.30 */3132/** 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";3435/** 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}4647/** 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}5859/** 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}7273/** 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}9091/** 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}102103/** 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}112113/** 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}122123/** Every group at once. Components extend only the groups they apply (see the top of this file). */124interface Base3DComponentProps125 extends CursorProps,126 TiltProps,127 Text3DProps,128 MaterialProps,129 MotionProps,130 EnvironmentProps,131 PerformanceProps {}132133type Defaults = Required<Omit<Base3DComponentProps, "text" | "fontUrl" | "particleCount" | "cameraFov">>;134135/** 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};164165/** 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};174175interface BackgroundCanvasProps extends Omit<CanvasProps, "children" | "style" | "frameloop" | "gl">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {176 children: ReactNode;177}178179/**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 WebGL184 * 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 paused189 const [inView, setInView] = useState(true);190 const [reducedMotion, setReducedMotion] = useState(false);191192 useEffect(() => {193 const el = containerRef.current;194 if (!el) return undefined;195 const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting));196 observer.observe(el);197198 const query = window.matchMedia("(prefers-reduced-motion: reduce)");199 const sync = () => setReducedMotion(query.matches);200 sync();201 query.addEventListener("change", sync);202203 return () => {204 observer.disconnect();205 query.removeEventListener("change", sync);206 };207 }, []);208209 return (210 <div ref={containerRef} style={FILL_STYLE} aria-hidden="true">211 <Canvas212 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}223224interface CanvasPointer {225 /** Pointer position in normalized device coordinates of the canvas (-1..1). */226 ndc: THREE.Vector2;227 /** True while the pointer is over the canvas area. */228 inside: boolean;229 /** True while a button is held down. */230 pressed: boolean;231}232233/**234 * Tracks the pointer relative to the canvas through window listeners: the235 * canvas itself has `pointer-events: none`, so R3F's own events never fire.236 * Returns a ref read inside useFrame — pointer moves never re-render React.237 */238function useCanvasPointer(onDown?: (ndc: THREE.Vector2) => void): RefObject<CanvasPointer> {239 const gl = useThree((state) => state.gl);240 const pointer = useRef<CanvasPointer>({ ndc: new THREE.Vector2(), inside: false, pressed: false });241 const onDownRef = useRef(onDown);242243 useEffect(() => {244 onDownRef.current = onDown;245 }, [onDown]);246247 useEffect(() => {248 const el = gl.domElement;249 const update = (event: PointerEvent) => {250 const rect = el.getBoundingClientRect();251 const p = pointer.current;252 p.ndc.set(((event.clientX - rect.left) / rect.width) * 2 - 1, -((event.clientY - rect.top) / rect.height) * 2 + 1);253 p.inside = Math.abs(p.ndc.x) <= 1 && Math.abs(p.ndc.y) <= 1;254 };255 const down = (event: PointerEvent) => {256 update(event);257 pointer.current.pressed = true;258 if (pointer.current.inside) onDownRef.current?.(pointer.current.ndc);259 };260 const up = () => {261 pointer.current.pressed = false;262 };263 const leave = () => {264 pointer.current.inside = false;265 pointer.current.pressed = false;266 };267268 window.addEventListener("pointermove", update, { passive: true });269 window.addEventListener("pointerdown", down, { passive: true });270 window.addEventListener("pointerup", up, { passive: true });271 document.documentElement.addEventListener("pointerleave", leave);272 window.addEventListener("blur", leave);273 return () => {274 window.removeEventListener("pointermove", update);275 window.removeEventListener("pointerdown", down);276 window.removeEventListener("pointerup", up);277 document.documentElement.removeEventListener("pointerleave", leave);278 window.removeEventListener("blur", leave);279 };280 }, [gl]);281282 return pointer;283}284285const unprojected = new THREE.Vector3();286287const rayDirection = new THREE.Vector3();288289/** Screen (NDC) → world space: intersects the camera ray with the plane z = planeZ. */290function ndcToWorldOnPlane(ndc: THREE.Vector2, camera: THREE.Camera, planeZ: number, target: THREE.Vector3) {291 unprojected.set(ndc.x, ndc.y, 0.5).unproject(camera);292 rayDirection.copy(unprojected).sub(camera.position).normalize();293 const distance = (planeZ - camera.position.z) / rayDirection.z;294 return target.copy(camera.position).addScaledVector(rayDirection, distance);295}296297/**298 * Shared GLSL noise functions, injected into the background shaders as strings.299 *300 * Both are the classic webgl-noise implementations by Ian McEwan and Stefan301 * Gustavson (Ashima Arts), MIT License — https://github.com/ashima/webgl-noise302 */303304/** 3D simplex noise: `float snoise(vec3 v)`, returns roughly -1..1. */305const SIMPLEX_3D = /* glsl */ `306vec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }307vec4 mod289(vec4 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }308vec4 permute(vec4 x) { return mod289(((x * 34.0) + 10.0) * x); }309vec4 taylorInvSqrt(vec4 r) { return 1.79284291400159 - 0.85373472095314 * r; }310311float snoise(vec3 v) {312 const vec2 C = vec2(1.0 / 6.0, 1.0 / 3.0);313 const vec4 D = vec4(0.0, 0.5, 1.0, 2.0);314315 vec3 i = floor(v + dot(v, C.yyy));316 vec3 x0 = v - i + dot(i, C.xxx);317318 vec3 g = step(x0.yzx, x0.xyz);319 vec3 l = 1.0 - g;320 vec3 i1 = min(g.xyz, l.zxy);321 vec3 i2 = max(g.xyz, l.zxy);322323 vec3 x1 = x0 - i1 + C.xxx;324 vec3 x2 = x0 - i2 + C.yyy;325 vec3 x3 = x0 - D.yyy;326327 i = mod289(i);328 vec4 p = permute(permute(permute(329 i.z + vec4(0.0, i1.z, i2.z, 1.0))330 + i.y + vec4(0.0, i1.y, i2.y, 1.0))331 + i.x + vec4(0.0, i1.x, i2.x, 1.0));332333 float n_ = 0.142857142857;334 vec3 ns = n_ * D.wyz - D.xzx;335336 vec4 j = p - 49.0 * floor(p * ns.z * ns.z);337 vec4 x_ = floor(j * ns.z);338 vec4 y_ = floor(j - 7.0 * x_);339340 vec4 x = x_ * ns.x + ns.yyyy;341 vec4 y = y_ * ns.x + ns.yyyy;342 vec4 h = 1.0 - abs(x) - abs(y);343344 vec4 b0 = vec4(x.xy, y.xy);345 vec4 b1 = vec4(x.zw, y.zw);346 vec4 s0 = floor(b0) * 2.0 + 1.0;347 vec4 s1 = floor(b1) * 2.0 + 1.0;348 vec4 sh = -step(h, vec4(0.0));349350 vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;351 vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww;352353 vec3 p0 = vec3(a0.xy, h.x);354 vec3 p1 = vec3(a0.zw, h.y);355 vec3 p2 = vec3(a1.xy, h.z);356 vec3 p3 = vec3(a1.zw, h.w);357358 vec4 norm = taylorInvSqrt(vec4(dot(p0, p0), dot(p1, p1), dot(p2, p2), dot(p3, p3)));359 p0 *= norm.x;360 p1 *= norm.y;361 p2 *= norm.z;362 p3 *= norm.w;363364 vec4 m = max(0.5 - vec4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0);365 m = m * m;366 return 105.0 * dot(m * m, vec4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3)));367}368`;369370export interface ParticleFieldProps extends Pick<MotionProps, "particleCount">, Pick<CursorProps, "cursorRadius">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {371 /** Number of particles. Default 5000. */372 particleCount?: number;373 /** @deprecated Use `particleCount`. */374 count?: number;375 /** Point size in pixels, for a particle 10 units from the camera. Default 4. */376 particleSize?: number;377 colorA?: string;378 colorB?: string;379 /** Multiplier on the noise flow speed. Default 1. */380 speed?: number;381 /** Radius of the cursor's influence, in world units. Default 2. */382 cursorRadius?: number;383 /** @deprecated Use `cursorRadius`. */384 mouseRadius?: number;385 /** Adds a bloom pass (@react-three/postprocessing). Default false. */386 enableBloom?: boolean;387}388389const vertexShader = /* glsl */ `390uniform float uTime;391uniform float uSize;392uniform float uPixelRatio;393uniform float uSpeed;394uniform vec3 uSpread;395uniform vec3 uMouse;396uniform float uMouseRadius;397uniform float uMouseForce;398399attribute float aRandom;400attribute float aScale;401402varying float vMix;403varying float vAlpha;404405${SIMPLEX_3D}406407void main() {408 // Positions are stored in -1..1 and stretched to the current viewport, so a resize never rebuilds the geometry409 vec3 p = position * uSpread;410411 // Smooth flow: three decorrelated simplex samples act as a displacement field412 float t = uTime * uSpeed * 0.15;413 vec3 q = p * 0.18 + aRandom * 10.0;414 vec3 flow = vec3(415 snoise(q + vec3(t, 0.0, 0.0)),416 snoise(q + vec3(0.0, t, 31.4)),417 snoise(q + vec3(17.1, 0.0, t))418 );419 p += flow * 0.9;420421 // Cursor: repulsion while hovering (force > 0), attraction while pressed (force < 0)422 vec2 toParticle = p.xy - uMouse.xy;423 float dist = length(toParticle);424 float falloff = 1.0 - smoothstep(0.0, uMouseRadius, dist);425 float push = falloff * falloff * uMouseRadius * 0.6 * uMouseForce;426 push = max(push, -dist * 0.85); // attraction never overshoots past the cursor427 vec2 direction = dist > 0.0001 ? toParticle / dist : vec2(0.0);428 p.xy += direction * push;429430 vec4 mvPosition = modelViewMatrix * vec4(p, 1.0);431 gl_Position = projectionMatrix * mvPosition;432 gl_PointSize = uSize * aScale * uPixelRatio * (10.0 / -mvPosition.z);433434 vMix = clamp(flow.x * 0.5 + 0.5 + (aRandom - 0.5) * 0.4, 0.0, 1.0);435 vAlpha = mix(0.75, 1.0, falloff * abs(uMouseForce));436}437`;438439const fragmentShader = /* glsl */ `440uniform vec3 uColorA;441uniform vec3 uColorB;442443varying float vMix;444varying float vAlpha;445446void main() {447 // Soft round sprite448 float d = length(gl_PointCoord - 0.5);449 float alpha = 1.0 - smoothstep(0.0, 0.5, d);450 if (alpha < 0.01) discard;451 gl_FragColor = vec4(mix(uColorA, uColorB, vMix), alpha * vAlpha);452 #include <colorspace_fragment>453}454`;455456const ParticleMaterial = shaderMaterial(457 {458 uTime: 0,459 uSize: 3,460 uPixelRatio: 1,461 uSpeed: 1,462 uSpread: new THREE.Vector3(8, 5, 2.5),463 uMouse: new THREE.Vector3(),464 uMouseRadius: 2,465 uMouseForce: 0,466 uColorA: new THREE.Color(),467 uColorB: new THREE.Color(),468 },469 vertexShader,470 fragmentShader471);472473type ParticleSystemProps = Required<Omit<ParticleFieldProps, "particleCount" | "cursorRadius" | "pauseWhenOffscreen" | "lowPowerMode" | "enableBloom">>;474475const ParticleSystem = memo(function ParticleSystem({ count, particleSize, colorA, colorB, speed, mouseRadius }: ParticleSystemProps) {476 const pointer = useCanvasPointer();477 const mouseWorld = useMemo(() => new THREE.Vector3(), []);478479 const geometry = useMemo(() => {480 const positions = new Float32Array(count * 3);481 const randoms = new Float32Array(count);482 const scales = new Float32Array(count);483 for (let i = 0; i < count; i++) {484 positions[i * 3] = Math.random() * 2 - 1;485 positions[i * 3 + 1] = Math.random() * 2 - 1;486 positions[i * 3 + 2] = Math.random() * 2 - 1;487 randoms[i] = Math.random();488 // Mostly small particles, a few larger ones489 scales[i] = 0.6 + Math.pow(Math.random(), 3) * 1.8;490 }491 const g = new THREE.BufferGeometry();492 g.setAttribute("position", new THREE.BufferAttribute(positions, 3));493 g.setAttribute("aRandom", new THREE.BufferAttribute(randoms, 1));494 g.setAttribute("aScale", new THREE.BufferAttribute(scales, 1));495 return g;496 }, [count]);497498 const material = useMemo(() => {499 const m = new ParticleMaterial();500 m.transparent = true;501 m.depthWrite = false;502 m.blending = THREE.AdditiveBlending;503 return m;504 }, []);505506 // Props → uniforms, without recreating the material507 useEffect(() => {508 const u = material.uniforms;509 u.uSize.value = particleSize;510 u.uSpeed.value = speed;511 u.uMouseRadius.value = mouseRadius;512 (u.uColorA.value as THREE.Color).set(colorA);513 (u.uColorB.value as THREE.Color).set(colorB);514 }, [material, particleSize, speed, mouseRadius, colorA, colorB]);515516 useEffect(() => () => geometry.dispose(), [geometry]);517 useEffect(() => () => material.dispose(), [material]);518519 useFrame((state, delta) => {520 const u = material.uniforms;521 u.uTime.value = state.clock.elapsedTime;522 u.uPixelRatio.value = state.viewport.dpr;523 (u.uSpread.value as THREE.Vector3).set(state.viewport.width * 0.55, state.viewport.height * 0.55, 2.5);524525 const p = pointer.current;526 const targetForce = p.inside ? (p.pressed ? -1 : 1) : 0;527 u.uMouseForce.value = THREE.MathUtils.damp(u.uMouseForce.value as number, targetForce, 4, delta);528 if (p.inside) {529 ndcToWorldOnPlane(p.ndc, state.camera, 0, mouseWorld);530 (u.uMouse.value as THREE.Vector3).lerp(mouseWorld, 1 - Math.exp(-10 * delta));531 }532 });533534 return <points geometry={geometry} material={material} frustumCulled={false} />;535});536537function ParticleFieldBackground({538 particleCount,539 count = particleCount ?? 5000,540 particleSize = 4,541 colorA = "#7dd3fc",542 colorB = "#c084fc",543 speed = 1,544 cursorRadius,545 mouseRadius = cursorRadius ?? 2,546 enableBloom = false,547 pauseWhenOffscreen,548 lowPowerMode,549}: ParticleFieldProps) {550 return (551 <BackgroundCanvas pauseWhenOffscreen={pauseWhenOffscreen} lowPowerMode={lowPowerMode} camera={{ position: [0, 0, 10], fov: 50 }}>552 <ParticleSystem553 count={count}554 particleSize={particleSize}555 colorA={colorA}556 colorB={colorB}557 speed={speed}558 mouseRadius={mouseRadius}559 />560 {enableBloom ? (561 <EffectComposer multisampling={0}>562 <Bloom mipmapBlur intensity={1.1} luminanceThreshold={0.15} luminanceSmoothing={0.3} />563 </EffectComposer>564 ) : null}565 </BackgroundCanvas>566 );567}568569export default memo(ParticleFieldBackground);
03
Drop it in a page
Updated live with the settings above.
app/page.tsx
1import ParticleFieldBackground from "@/components/ParticleFieldBackground";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 <ParticleFieldBackground8 particleCount={5000}9 particleSize={4}10 speed={1}11 cursorRadius={2}12 colorA="#7dd3fc"13 colorB="#c084fc"14 />15 </div>16 );17}