← All components Next componentFloating Shapes→
Background · Fluid
Organic Fluid
Raymarched metaballs merging like a lava lamp; one of them follows the cursor.
<OrganicFluidBackground />Live
One blob follows your cursor
Customize
Color 1#6d28d9
Color 2#f0abfc
Installation
Use it in your project
Or skip the copy-paste
One command: writes the file and installs the dependencies.
$ npx deepui-cli add organic-fluid
01
Install
The 3D packages this component is built on.
$ npm install three @react-three/fiber && npm install -D @types/three
02
Add the component
One self-contained file: create components/OrganicFluidBackground.tsx and paste it in.
components/OrganicFluidBackground.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";1516/**17 * The shared props API of DeepUI's individual 3D components (not the full-page templates, which keep18 * their own tailored scenes).19 *20 * The props are grouped by concern. A component extends ONLY the groups it really applies, so its21 * type never advertises a knob that does nothing (a card has no particles, a background has no tilt):22 *23 * interface MyCardProps extends CursorProps, TiltProps, MaterialProps, PerformanceProps { … }24 *25 * `Base3DComponentProps` is every group at once, for tooling that handles any component. Same name,26 * same unit and same meaning everywhere; the default values live in DEFAULT_3D_PROPS. These files are27 * inlined into each component's single-file bundle (lib/bundle-source.mjs), only what it uses.28 */2930/** Which rotation axes follow the pointer. "x-only": the object nods (up / down); "y-only": it turns (left / right). */31export type TiltAxis = "both" | "x-only" | "y-only" | "none";3233/** 1. Cursor: how the pointer pulls, pushes and drags the object. */34interface CursorProps {35 /** 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). */36 cursorRadius?: number;37 /** Positive pulls things towards the pointer, negative pushes them away (repulsion, shockwave). Default 1. */38 cursorForce?: number;39 /** How far the object slides towards the pointer, 0 (stays put) to 1 (follows closely). Default 0. */40 magneticStrength?: number;41 /** Share of the remaining distance the motion closes each frame (at 60 fps), 0.01 (heavy, slow) to 1 (instant). Default 0.1. */42 cursorDamping?: number;43}4445/** 2. Tilt and parallax: the object leans towards the pointer, its layers slide against each other. */46interface TiltProps {47 /** Largest lean towards the pointer, in degrees. Default 15. */48 maxTiltAngle?: number;49 /** Axes that follow the pointer. Default "both". */50 tiltAxis?: TiltAxis;51 /** Lean away from the pointer instead of towards it. Default false. */52 invertTilt?: boolean;53 /** How far apart the depth layers slide when the object tilts, 0 (flat) to 2. Default 1. */54 parallaxOffset?: number;55}5657/** 3. Text and 3D typography, for components that draw a label. */58interface Text3DProps {59 /** The label drawn by the component. */60 text?: string;61 /** Scale of the lettering. Default 1. */62 fontSize?: number;63 /** Extrusion depth of 3D letters. Default 0.2. */64 textDepth?: number;65 /** Bevelled, light-catching edges on 3D letters. Default true. */66 bevelEnabled?: boolean;67 /** Custom font: a .woff / .ttf (flat text) or a typeface .json (extruded text). */68 fontUrl?: string;69}7071/** 4. Rendering, materials and glow. */72interface MaterialProps {73 /** Main color of the object. Default "#6366f1". */74 primaryColor?: string;75 /** Color of the glow. Default "#00f0ff". */76 emissiveColor?: string;77 /** Strength of the glow, 0 (none) to 3. Default 1. */78 emissiveIntensity?: number;79 /** 0 (mirror, glass) to 1 (matte). Default 0.3. */80 roughness?: number;81 /** 0 (plastic, organic) to 1 (metal). Default 0.5. */82 metalness?: number;83 /** 0 (opaque) to 1 (clear glass): see-through, refracting surfaces. Default 0. */84 transmission?: number;85 /** Technical wireframe rendering. Default false. */86 wireframe?: boolean;87}8889/** 5. Particles, idle motion and shader animation. */90interface MotionProps {91 /** Number of instanced elements. Default depends on the component. */92 particleCount?: number;93 /** Spin on its own, in radians per second (negative: the other way; 0.5 ≈ one turn in 12 s). Default 0. */94 autoRotateSpeed?: number;95 /** Pulses or ripples per second. Default 1. */96 pulseRate?: number;97 /** Amplitude of the noise deformation, 0 (none) to 2. Default 1. */98 displacementScale?: number;99}100101/** 6. Environment and camera. */102interface EnvironmentProps {103 /** Camera field of view, in degrees. Default depends on the component. */104 cameraFov?: number;105 /** Color of the depth fog. Default "#0a0a0a". */106 fogColor?: string;107 /** Thickness of the fog, 0 (none) to 0.2. Default 0. */108 fogDensity?: number;109}110111/** 7. Performance and accessibility. */112interface PerformanceProps {113 /** Lighter rendering for weak devices: pixel ratio 1, fewer instances, smaller environment maps. Default false. */114 lowPowerMode?: boolean;115 /** Under the OS "reduce motion" setting, stop idle spin, pulses and deformation (pointer feedback stays). Default true. */116 respectReducedMotion?: boolean;117 /** Stop the render loop while the component is scrolled out of view. Default true. */118 pauseWhenOffscreen?: boolean;119}120121/** Every group at once. Components extend only the groups they apply (see the top of this file). */122interface Base3DComponentProps123 extends CursorProps,124 TiltProps,125 Text3DProps,126 MaterialProps,127 MotionProps,128 EnvironmentProps,129 PerformanceProps {}130131type Defaults = Required<Omit<Base3DComponentProps, "text" | "fontUrl" | "particleCount" | "cameraFov">>;132133/** The values a prop takes when it is left out. A component may override one, and then documents it. */134const DEFAULT_3D_PROPS: Defaults = {135 cursorRadius: 220,136 cursorForce: 1,137 magneticStrength: 0,138 cursorDamping: 0.1,139 maxTiltAngle: 15,140 tiltAxis: "both",141 invertTilt: false,142 parallaxOffset: 1,143 fontSize: 1,144 textDepth: 0.2,145 bevelEnabled: true,146 primaryColor: "#6366f1",147 emissiveColor: "#00f0ff",148 emissiveIntensity: 1,149 roughness: 0.3,150 metalness: 0.5,151 transmission: 0,152 wireframe: false,153 autoRotateSpeed: 0,154 pulseRate: 1,155 displacementScale: 1,156 fogColor: "#0a0a0a",157 fogDensity: 0,158 lowPowerMode: false,159 respectReducedMotion: true,160 pauseWhenOffscreen: true,161};162163/** Fills the positioned parent; never intercepts clicks meant for the page content above it. */164const FILL_STYLE: CSSProperties = {165 position: "absolute",166 top: 0,167 left: 0,168 width: "100%",169 height: "100%",170 pointerEvents: "none",171};172173interface BackgroundCanvasProps extends Omit<CanvasProps, "children" | "style" | "frameloop" | "gl">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {174 children: ReactNode;175}176177/**178 * Ready-to-use <Canvas> shared by every background.179 * - Pauses the render loop while the canvas is scrolled out of view.180 * - Renders a single still frame when the user prefers reduced motion.181 * - Caps the pixel ratio; R3F disposes the renderer and releases the WebGL182 * context (forceContextLoss) when the Canvas unmounts.183 */184function BackgroundCanvas({ children, dpr = [1, 1.75], pauseWhenOffscreen = DEFAULT_3D_PROPS.pauseWhenOffscreen, lowPowerMode = DEFAULT_3D_PROPS.lowPowerMode, ...canvasProps }: BackgroundCanvasProps) {185 const containerRef = useRef<HTMLDivElement>(null);186 // Starts "in view" so the first frame is always drawn before the loop can be paused187 const [inView, setInView] = useState(true);188 const [reducedMotion, setReducedMotion] = useState(false);189190 useEffect(() => {191 const el = containerRef.current;192 if (!el) return undefined;193 const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting));194 observer.observe(el);195196 const query = window.matchMedia("(prefers-reduced-motion: reduce)");197 const sync = () => setReducedMotion(query.matches);198 sync();199 query.addEventListener("change", sync);200201 return () => {202 observer.disconnect();203 query.removeEventListener("change", sync);204 };205 }, []);206207 return (208 <div ref={containerRef} style={FILL_STYLE} aria-hidden="true">209 <Canvas210 dpr={lowPowerMode ? 1 : dpr}211 frameloop={!inView && pauseWhenOffscreen ? "never" : reducedMotion ? "demand" : "always"}212 gl={{ antialias: true, alpha: true, powerPreference: "high-performance" }}213 style={{ pointerEvents: "none" }}214 {...canvasProps}215 >216 {children}217 </Canvas>218 </div>219 );220}221222interface CanvasPointer {223 /** Pointer position in normalized device coordinates of the canvas (-1..1). */224 ndc: THREE.Vector2;225 /** True while the pointer is over the canvas area. */226 inside: boolean;227 /** True while a button is held down. */228 pressed: boolean;229}230231/**232 * Tracks the pointer relative to the canvas through window listeners: the233 * canvas itself has `pointer-events: none`, so R3F's own events never fire.234 * Returns a ref read inside useFrame — pointer moves never re-render React.235 */236function useCanvasPointer(onDown?: (ndc: THREE.Vector2) => void): RefObject<CanvasPointer> {237 const gl = useThree((state) => state.gl);238 const pointer = useRef<CanvasPointer>({ ndc: new THREE.Vector2(), inside: false, pressed: false });239 const onDownRef = useRef(onDown);240241 useEffect(() => {242 onDownRef.current = onDown;243 }, [onDown]);244245 useEffect(() => {246 const el = gl.domElement;247 const update = (event: PointerEvent) => {248 const rect = el.getBoundingClientRect();249 const p = pointer.current;250 p.ndc.set(((event.clientX - rect.left) / rect.width) * 2 - 1, -((event.clientY - rect.top) / rect.height) * 2 + 1);251 p.inside = Math.abs(p.ndc.x) <= 1 && Math.abs(p.ndc.y) <= 1;252 };253 const down = (event: PointerEvent) => {254 update(event);255 pointer.current.pressed = true;256 if (pointer.current.inside) onDownRef.current?.(pointer.current.ndc);257 };258 const up = () => {259 pointer.current.pressed = false;260 };261 const leave = () => {262 pointer.current.inside = false;263 pointer.current.pressed = false;264 };265266 window.addEventListener("pointermove", update, { passive: true });267 window.addEventListener("pointerdown", down, { passive: true });268 window.addEventListener("pointerup", up, { passive: true });269 document.documentElement.addEventListener("pointerleave", leave);270 window.addEventListener("blur", leave);271 return () => {272 window.removeEventListener("pointermove", update);273 window.removeEventListener("pointerdown", down);274 window.removeEventListener("pointerup", up);275 document.documentElement.removeEventListener("pointerleave", leave);276 window.removeEventListener("blur", leave);277 };278 }, [gl]);279280 return pointer;281}282283export interface FluidProps extends Pick<MotionProps, "particleCount">, Pick<MaterialProps, "primaryColor" | "roughness">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {284 /** Number of metaballs, 1–8. Default 5. */285 particleCount?: number;286 /** @deprecated Use `particleCount`. */287 blobCount?: number;288 primaryColor?: string;289 /** @deprecated Use `primaryColor`. */290 colorPrimary?: string;291 colorSecondary?: string;292 /** 0 = glossy, 1 = matte. Default 0.25. */293 roughness?: number;294 /** Speed of the deformation and of the blobs merging. Default 1. */295 viscosity?: number;296 /** The first blob follows the cursor. Default true. */297 interactive?: boolean;298}299300const MAX_BLOBS = 8;301302const vertexShader = /* glsl */ `303void main() {304 // Full-screen quad: the plane's -1..1 vertices are already in clip space, no camera involved305 gl_Position = vec4(position.xy, 0.0, 1.0);306}307`;308309const fragmentShader = /* glsl */ `310#define MAX_BLOBS ${MAX_BLOBS}311312uniform float uTime;313uniform float uViscosity;314uniform float uRoughness;315uniform int uCount;316uniform vec2 uResolution;317uniform vec3 uColorA;318uniform vec3 uColorB;319uniform vec3 uMouse; // xy: cursor on the z = 0 plane, z: influence 0..1320321float smin(float a, float b, float k) {322 float h = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0);323 return mix(b, a, h) - k * h * (1.0 - h);324}325326vec3 blobCenter(int index, float t) {327 float fi = float(index);328 return vec3(329 sin(t * (0.7 + 0.13 * fi) + fi * 1.7) * 1.6,330 cos(t * (0.53 + 0.11 * fi) + fi * 2.3) * 1.0,331 sin(t * (0.41 + 0.07 * fi) + fi) * 0.6332 );333}334335// Signed distance to the fluid: metaballs fused with a smooth minimum, plus a jelly wobble336float map(vec3 p) {337 float t = uTime * uViscosity;338 float d = 1e5;339 for (int i = 0; i < MAX_BLOBS; i++) {340 if (i >= uCount) break;341 vec3 center = blobCenter(i, t);342 if (i == 0) center = mix(center, vec3(uMouse.xy, 0.0), uMouse.z);343 float radius = 0.55 + 0.15 * sin(t * 1.3 + float(i) * 2.1);344 d = smin(d, length(p - center) - radius, 0.65);345 }346 d += 0.06 * sin(p.x * 3.1 + t * 1.7) * sin(p.y * 2.7 - t * 1.3) * sin(p.z * 3.3 + t);347 return d;348}349350vec3 calcNormal(vec3 p) {351 const vec2 k = vec2(1.0, -1.0);352 const float h = 0.001;353 return normalize(354 k.xyy * map(p + k.xyy * h) +355 k.yyx * map(p + k.yyx * h) +356 k.yxy * map(p + k.yxy * h) +357 k.xxx * map(p + k.xxx * h)358 );359}360361void main() {362 vec2 uv = (gl_FragCoord.xy - 0.5 * uResolution) / uResolution.y;363 vec3 rayOrigin = vec3(0.0, 0.0, 4.0);364 vec3 rayDirection = normalize(vec3(uv, -1.6));365366 float travelled = 0.0;367 bool hit = false;368 for (int i = 0; i < 72; i++) {369 float d = map(rayOrigin + rayDirection * travelled);370 if (d < 0.001) {371 hit = true;372 break;373 }374 travelled += d * 0.9; // under-step: the wobble makes the distance field slightly inexact375 if (travelled > 9.0) break;376 }377 if (!hit) discard;378379 vec3 p = rayOrigin + rayDirection * travelled;380 vec3 n = calcNormal(p);381 vec3 v = -rayDirection;382 vec3 l = normalize(vec3(0.6, 0.8, 0.7));383384 float diffuse = max(dot(n, l), 0.0);385 float shininess = mix(160.0, 6.0, uRoughness);386 float specular = pow(max(dot(n, normalize(l + v)), 0.0), shininess) * mix(1.0, 0.15, uRoughness);387 float fresnel = pow(1.0 - max(dot(n, v), 0.0), 3.0);388389 vec3 base = mix(uColorA, uColorB, smoothstep(-0.8, 0.8, n.y + 0.3 * sin(p.x * 1.5 + uTime * 0.3)));390 vec3 color = base * (0.25 + 0.75 * diffuse) + specular + fresnel * mix(uColorB, vec3(1.0), 0.5) * 0.9;391 gl_FragColor = vec4(color, 1.0);392 #include <colorspace_fragment>393}394`;395396type FluidSurfaceProps = Required<Omit<FluidProps, "particleCount" | "primaryColor" | "pauseWhenOffscreen" | "lowPowerMode">>;397398const FluidSurface = memo(function FluidSurface({399 blobCount,400 colorPrimary,401 colorSecondary,402 roughness,403 viscosity,404 interactive,405}: FluidSurfaceProps) {406 const pointer = useCanvasPointer();407408 const geometry = useMemo(() => new THREE.PlaneGeometry(2, 2), []);409 const material = useMemo(410 () =>411 new THREE.ShaderMaterial({412 uniforms: {413 uTime: { value: 0 },414 uViscosity: { value: 1 },415 uRoughness: { value: 0.25 },416 uCount: { value: 5 },417 uResolution: { value: new THREE.Vector2(1, 1) },418 uColorA: { value: new THREE.Color() },419 uColorB: { value: new THREE.Color() },420 uMouse: { value: new THREE.Vector3() },421 },422 vertexShader,423 fragmentShader,424 transparent: true,425 depthWrite: false,426 depthTest: false,427 }),428 []429 );430431 useEffect(() => {432 const u = material.uniforms;433 u.uCount.value = THREE.MathUtils.clamp(Math.round(blobCount), 1, MAX_BLOBS);434 u.uViscosity.value = viscosity;435 u.uRoughness.value = THREE.MathUtils.clamp(roughness, 0, 1);436 (u.uColorA.value as THREE.Color).set(colorPrimary);437 (u.uColorB.value as THREE.Color).set(colorSecondary);438 }, [material, blobCount, viscosity, roughness, colorPrimary, colorSecondary]);439440 useEffect(() => () => geometry.dispose(), [geometry]);441 useEffect(() => () => material.dispose(), [material]);442443 useFrame((state, delta) => {444 const u = material.uniforms;445 u.uTime.value = state.clock.elapsedTime;446 state.gl.getDrawingBufferSize(u.uResolution.value as THREE.Vector2);447448 // Cursor → raymarch space: same projection as the shader (camera at z = 4, focal length 1.6),449 // so a point on the z = 0 plane sits at uv * 4 / 1.6450 const mouse = u.uMouse.value as THREE.Vector3;451 const p = pointer.current;452 const active = interactive && p.inside;453 if (active) {454 const aspect = state.size.width / state.size.height;455 mouse.x = THREE.MathUtils.damp(mouse.x, p.ndc.x * 0.5 * aspect * 2.5, 6, delta);456 mouse.y = THREE.MathUtils.damp(mouse.y, p.ndc.y * 0.5 * 2.5, 6, delta);457 }458 mouse.z = THREE.MathUtils.damp(mouse.z, active ? 1 : 0, 3, delta);459 });460461 return <mesh geometry={geometry} material={material} frustumCulled={false} />;462});463464function OrganicFluidBackground({465 particleCount,466 blobCount = particleCount ?? 5,467 primaryColor,468 colorPrimary = primaryColor ?? "#6d28d9",469 colorSecondary = "#f0abfc",470 roughness = 0.25,471 viscosity = 1,472 interactive = true,473 pauseWhenOffscreen,474 lowPowerMode,475}: FluidProps) {476 return (477 // Full-screen raymarching costs one shader run per pixel: the pixel ratio is capped lower than the other backgrounds478 <BackgroundCanvas pauseWhenOffscreen={pauseWhenOffscreen} lowPowerMode={lowPowerMode} dpr={[1, 1.25]}>479 <FluidSurface480 blobCount={blobCount}481 colorPrimary={colorPrimary}482 colorSecondary={colorSecondary}483 roughness={roughness}484 viscosity={viscosity}485 interactive={interactive}486 />487 </BackgroundCanvas>488 );489}490491export default memo(OrganicFluidBackground);
03
Drop it in a page
Updated live with the settings above.
app/page.tsx
1import OrganicFluidBackground from "@/components/OrganicFluidBackground";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 <OrganicFluidBackground8 particleCount={5}9 viscosity={1}10 roughness={0.25}11 primaryColor="#6d28d9"12 colorSecondary="#f0abfc"13 />14 </div>15 );16}