← All components Next componentSingularity Fluid Orb→
Cursors · Liquid
Fluid Chroma Cursor
The Fluid Chroma Warp effect as a cursor: your pointer pours a trail of iridescent liquid oil over the page, each push in the next color of your palette, swirling and fading behind it.
Customize
Push 1#7c3aed
Push 2#22d3ee
Push 3#ec4899
Push 4#f5b94a
Installation
Use it in your project
Or skip the copy-paste
One command: writes the file and installs the dependencies.
$ npx deepui-cli add fluid-chroma-cursor
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/FluidChromaCursor.tsx and paste it in.
components/FluidChromaCursor.tsx
1"use client";23import { memo, useEffect, useMemo, useRef, useState, type CSSProperties, type RefObject } from "react";4import * as THREE from "three";5import { Canvas, useFrame, useThree } from "@react-three/fiber";67/** Full-viewport, click-through layer above the page. */8const OVERLAY_STYLE: CSSProperties = {9 position: "fixed",10 top: 0,11 left: 0,12 width: "100vw",13 height: "100vh",14 pointerEvents: "none",15 zIndex: 9999,16};1718/**19 * False on touch screens (`pointer: coarse`) and during server rendering: the custom cursor is not20 * drawn and the native cursor is left alone. Follows the media query live (tablet + mouse…).21 */22function useCursorEnabled() {23 const [enabled, setEnabled] = useState(false);24 useEffect(() => {25 const query = window.matchMedia("(pointer: coarse)");26 const sync = () => setEnabled(!query.matches);27 sync();28 query.addEventListener("change", sync);29 return () => query.removeEventListener("change", sync);30 }, []);31 return enabled;32}3334function usePrefersReducedMotion() {35 const [reduced, setReduced] = useState(false);36 useEffect(() => {37 const query = window.matchMedia("(prefers-reduced-motion: reduce)");38 const sync = () => setReduced(query.matches);39 sync();40 query.addEventListener("change", sync);41 return () => query.removeEventListener("change", sync);42 }, []);43 return reduced;44}4546/** Hides the system cursor on the whole page while `active` (restored on unmount). */47function useHideNativeCursor(active: boolean) {48 useEffect(() => {49 if (!active) return undefined;50 const style = document.createElement("style");51 style.setAttribute("data-custom-cursor", "");52 style.textContent = "*, *::before, *::after { cursor: none !important; }";53 document.head.appendChild(style);54 return () => style.remove();55 }, [active]);56}5758/** 7. Performance and accessibility. */59interface PerformanceProps {60 /** Lighter rendering for weak devices: pixel ratio 1, fewer instances, smaller environment maps. Default false. */61 lowPowerMode?: boolean;62 /** Under the OS "reduce motion" setting, stop idle spin, pulses and deformation (pointer feedback stays). Default true. */63 respectReducedMotion?: boolean;64 /** Stop the render loop while the component is scrolled out of view. Default true. */65 pauseWhenOffscreen?: boolean;66}6768interface CanvasPointer {69 /** Pointer position in normalized device coordinates of the canvas (-1..1). */70 ndc: THREE.Vector2;71 /** True while the pointer is over the canvas area. */72 inside: boolean;73 /** True while a button is held down. */74 pressed: boolean;75}7677/**78 * Tracks the pointer relative to the canvas through window listeners: the79 * canvas itself has `pointer-events: none`, so R3F's own events never fire.80 * Returns a ref read inside useFrame — pointer moves never re-render React.81 */82function useCanvasPointer(onDown?: (ndc: THREE.Vector2) => void): RefObject<CanvasPointer> {83 const gl = useThree((state) => state.gl);84 const pointer = useRef<CanvasPointer>({ ndc: new THREE.Vector2(), inside: false, pressed: false });85 const onDownRef = useRef(onDown);8687 useEffect(() => {88 onDownRef.current = onDown;89 }, [onDown]);9091 useEffect(() => {92 const el = gl.domElement;93 const update = (event: PointerEvent) => {94 const rect = el.getBoundingClientRect();95 const p = pointer.current;96 p.ndc.set(((event.clientX - rect.left) / rect.width) * 2 - 1, -((event.clientY - rect.top) / rect.height) * 2 + 1);97 p.inside = Math.abs(p.ndc.x) <= 1 && Math.abs(p.ndc.y) <= 1;98 };99 const down = (event: PointerEvent) => {100 update(event);101 pointer.current.pressed = true;102 if (pointer.current.inside) onDownRef.current?.(pointer.current.ndc);103 };104 const up = () => {105 pointer.current.pressed = false;106 };107 const leave = () => {108 pointer.current.inside = false;109 pointer.current.pressed = false;110 };111112 window.addEventListener("pointermove", update, { passive: true });113 window.addEventListener("pointerdown", down, { passive: true });114 window.addEventListener("pointerup", up, { passive: true });115 document.documentElement.addEventListener("pointerleave", leave);116 window.addEventListener("blur", leave);117 return () => {118 window.removeEventListener("pointermove", update);119 window.removeEventListener("pointerdown", down);120 window.removeEventListener("pointerup", up);121 document.documentElement.removeEventListener("pointerleave", leave);122 window.removeEventListener("blur", leave);123 };124 }, [gl]);125126 return pointer;127}128129// A GPU stable-fluids solver (Jos Stam's method, as popularised by Pavel Dobryakov's WebGL fluid):130// semi-Lagrangian advection, vorticity confinement, a Jacobi pressure solve. Shared by FluidChromaWarp,131// FluidSmokeDrift and FluidChromaCursor; each of them only adds its own splats and its own display.132133const baseVertex = /* glsl */ `134uniform vec2 uTexel;135varying vec2 vUv;136varying vec2 vL;137varying vec2 vR;138varying vec2 vT;139varying vec2 vB;140void main() {141 vUv = uv;142 vL = uv - vec2(uTexel.x, 0.0);143 vR = uv + vec2(uTexel.x, 0.0);144 vT = uv + vec2(0.0, uTexel.y);145 vB = uv - vec2(0.0, uTexel.y);146 gl_Position = vec4(position.xy, 0.0, 1.0);147}148`;149150const splatFragment = /* glsl */ `151uniform sampler2D uTarget;152uniform float uAspect;153uniform vec3 uColor;154uniform vec2 uPoint;155uniform float uRadius;156varying vec2 vUv;157void main() {158 vec2 p = vUv - uPoint;159 p.x *= uAspect;160 vec3 splat = exp(-dot(p, p) / uRadius) * uColor;161 gl_FragColor = vec4(texture2D(uTarget, vUv).xyz + splat, 1.0);162}163`;164165const advectFragment = /* glsl */ `166uniform sampler2D uVelocity;167uniform sampler2D uSource;168uniform vec2 uTexel;169uniform float uDt;170uniform float uDissipation;171uniform float uTopSink;172varying vec2 vUv;173void main() {174 vec2 coord = vUv - uDt * texture2D(uVelocity, vUv).xy * uTexel;175 // The top band drains (rising smoke leaves the frame instead of piling up against the edge)176 float sink = uTopSink * smoothstep(0.7, 1.0, vUv.y);177 gl_FragColor = texture2D(uSource, coord) / (1.0 + (uDissipation + sink) * uDt);178}179`;180181const curlFragment = /* glsl */ `182uniform sampler2D uVelocity;183varying vec2 vUv; varying vec2 vL; varying vec2 vR; varying vec2 vT; varying vec2 vB;184void main() {185 float l = texture2D(uVelocity, vL).y;186 float r = texture2D(uVelocity, vR).y;187 float t = texture2D(uVelocity, vT).x;188 float b = texture2D(uVelocity, vB).x;189 gl_FragColor = vec4(0.5 * (r - l - t + b), 0.0, 0.0, 1.0);190}191`;192193// Vorticity confinement (keeps the small eddies alive), the surface's own slow swirl (curl noise), and194// buoyancy: dye denser than nothing rises (smoke), in proportion to its red channel195const forcesFragment = /* glsl */ `196uniform sampler2D uVelocity;197uniform sampler2D uCurl;198uniform sampler2D uDye;199uniform float uCurlStrength;200uniform float uDt;201uniform float uTime;202uniform float uTurbulence;203uniform float uNoiseScale;204uniform float uBuoyancy;205varying vec2 vUv; varying vec2 vL; varying vec2 vR; varying vec2 vT; varying vec2 vB;206vec2 hash(vec2 p) { p = vec2(dot(p, vec2(127.1, 311.7)), dot(p, vec2(269.5, 183.3))); return -1.0 + 2.0 * fract(sin(p) * 43758.5453); }207float noise(vec2 p) {208 vec2 i = floor(p); vec2 f = fract(p); vec2 u = f * f * (3.0 - 2.0 * f);209 return mix(mix(dot(hash(i), f), dot(hash(i + vec2(1, 0)), f - vec2(1, 0)), u.x),210 mix(dot(hash(i + vec2(0, 1)), f - vec2(0, 1)), dot(hash(i + vec2(1, 1)), f - vec2(1, 1)), u.x), u.y);211}212void main() {213 float l = texture2D(uCurl, vL).x;214 float r = texture2D(uCurl, vR).x;215 float t = texture2D(uCurl, vT).x;216 float b = texture2D(uCurl, vB).x;217 float c = texture2D(uCurl, vUv).x;218 vec2 force = 0.5 * vec2(abs(t) - abs(b), abs(r) - abs(l));219 force /= length(force) + 1e-4;220 force *= uCurlStrength * c;221 force.y *= -1.0;222 // Curl of a drifting noise field: divergence-free, it stirs without pumping223 vec2 q = vUv * uNoiseScale + vec2(uTime * 0.05, -uTime * 0.04);224 float e = 0.01;225 float n1 = noise(q + vec2(0.0, e)), n2 = noise(q - vec2(0.0, e));226 float n3 = noise(q + vec2(e, 0.0)), n4 = noise(q - vec2(e, 0.0));227 vec2 swirl = vec2(n1 - n2, -(n3 - n4)) / (2.0 * e);228 float density = texture2D(uDye, vUv).r;229 vec2 v = texture2D(uVelocity, vUv).xy + (force + swirl * uTurbulence * 6.0 + vec2(0.0, density * uBuoyancy)) * uDt;230 gl_FragColor = vec4(clamp(v, -1000.0, 1000.0), 0.0, 1.0);231}232`;233234const divergenceFragment = /* glsl */ `235uniform sampler2D uVelocity;236varying vec2 vUv; varying vec2 vL; varying vec2 vR; varying vec2 vT; varying vec2 vB;237void main() {238 float l = texture2D(uVelocity, vL).x;239 float r = texture2D(uVelocity, vR).x;240 float t = texture2D(uVelocity, vT).y;241 float b = texture2D(uVelocity, vB).y;242 vec2 c = texture2D(uVelocity, vUv).xy;243 if (vL.x < 0.0) l = -c.x;244 if (vR.x > 1.0) r = -c.x;245 if (vT.y > 1.0) t = -c.y;246 if (vB.y < 0.0) b = -c.y;247 gl_FragColor = vec4(0.5 * (r - l + t - b), 0.0, 0.0, 1.0);248}249`;250251const pressureFragment = /* glsl */ `252uniform sampler2D uPressure;253uniform sampler2D uDivergence;254varying vec2 vUv; varying vec2 vL; varying vec2 vR; varying vec2 vT; varying vec2 vB;255void main() {256 float l = texture2D(uPressure, vL).x;257 float r = texture2D(uPressure, vR).x;258 float t = texture2D(uPressure, vT).x;259 float b = texture2D(uPressure, vB).x;260 float d = texture2D(uDivergence, vUv).x;261 gl_FragColor = vec4((l + r + b + t - d) * 0.25, 0.0, 0.0, 1.0);262}263`;264265const gradientFragment = /* glsl */ `266uniform sampler2D uPressure;267uniform sampler2D uVelocity;268varying vec2 vUv; varying vec2 vL; varying vec2 vR; varying vec2 vT; varying vec2 vB;269void main() {270 float l = texture2D(uPressure, vL).x;271 float r = texture2D(uPressure, vR).x;272 float t = texture2D(uPressure, vT).x;273 float b = texture2D(uPressure, vB).x;274 vec2 v = texture2D(uVelocity, vUv).xy - vec2(r - l, t - b);275 gl_FragColor = vec4(v, 0.0, 1.0);276}277`;278279const scaleFragment = /* glsl */ `280uniform sampler2D uSource;281uniform float uValue;282varying vec2 vUv;283void main() { gl_FragColor = uValue * texture2D(uSource, vUv); }284`;285286interface DoubleTarget {287 read: THREE.WebGLRenderTarget;288 write: THREE.WebGLRenderTarget;289 swap: () => void;290 dispose: () => void;291}292293function createTarget(w: number, h: number) {294 return new THREE.WebGLRenderTarget(w, h, {295 type: THREE.HalfFloatType,296 format: THREE.RGBAFormat,297 minFilter: THREE.LinearFilter,298 magFilter: THREE.LinearFilter,299 wrapS: THREE.ClampToEdgeWrapping,300 wrapT: THREE.ClampToEdgeWrapping,301 depthBuffer: false,302 });303}304305function createDouble(w: number, h: number): DoubleTarget {306 const t: DoubleTarget = {307 read: createTarget(w, h),308 write: createTarget(w, h),309 swap() {310 const r = t.read;311 t.read = t.write;312 t.write = r;313 },314 dispose() {315 t.read.dispose();316 t.write.dispose();317 },318 };319 return t;320}321322/** A material for one solver pass, or for a component's own display pass. */323function fluidPass(fragmentShader: string, uniforms: Record<string, THREE.IUniform>, options: Partial<THREE.ShaderMaterialParameters> = {}) {324 return new THREE.ShaderMaterial({325 vertexShader: baseVertex,326 fragmentShader,327 uniforms: { uTexel: { value: new THREE.Vector2() }, ...uniforms },328 depthTest: false,329 depthWrite: false,330 ...options,331 });332}333334interface FluidResolution {335 /** Velocity / pressure grid, on the short side of the canvas. */336 sim: number;337 /** Dye (color) grid, on the short side of the canvas. */338 dye: number;339 /** Jacobi iterations of the pressure solve. */340 iterations: number;341}342343interface FluidStep {344 dt: number;345 time: number;346 /** How fast the motion dies out (per second). */347 velocityDissipation: number;348 /** How fast the dye fades (per second). */349 dyeDissipation: number;350 /** Vorticity confinement strength. Default 24. */351 curl?: number;352 /** Strength of the idle curl-noise swirl. Default 0. */353 turbulence?: number;354 /** Size of the idle swirls: noise cells across the canvas. Default 3. */355 noiseScale?: number;356 /** Upward force per unit of dye (red channel). Default 0. */357 buoyancy?: number;358 /** Extra dye fading (per second) in the top 30% of the canvas, strongest at the edge. Default 0. */359 topSink?: number;360}361362interface SplatColor {363 r: number;364 g: number;365 b: number;366}367368/** The fluid's state on the GPU and the passes that move it forward. Created and disposed by useFluidSolver. */369class FluidSolver {370 readonly aspect: number;371 readonly simTexel: THREE.Vector2;372 readonly dyeTexel: THREE.Vector2;373 private readonly gl: THREE.WebGLRenderer;374 private readonly iterations: number;375 private readonly velocity: DoubleTarget;376 private readonly dye: DoubleTarget;377 private readonly pressure: DoubleTarget;378 private readonly divergence: THREE.WebGLRenderTarget;379 private readonly curl: THREE.WebGLRenderTarget;380 private readonly passes;381 private readonly geometry = new THREE.PlaneGeometry(2, 2);382 private readonly mesh: THREE.Mesh;383 private readonly scene = new THREE.Scene();384 private readonly camera = new THREE.Camera();385386 constructor(gl: THREE.WebGLRenderer, width: number, height: number, resolution: FluidResolution) {387 this.gl = gl;388 this.iterations = resolution.iterations;389 this.aspect = Math.max(width, 1) / Math.max(height, 1);390 const grid = (n: number) => [Math.round(n * Math.max(this.aspect, 1)), Math.round(n / Math.min(this.aspect, 1))] as const;391 const [simW, simH] = grid(resolution.sim);392 const [dyeW, dyeH] = grid(resolution.dye);393 this.simTexel = new THREE.Vector2(1 / simW, 1 / simH);394 this.dyeTexel = new THREE.Vector2(1 / dyeW, 1 / dyeH);395 this.velocity = createDouble(simW, simH);396 this.dye = createDouble(dyeW, dyeH);397 this.pressure = createDouble(simW, simH);398 this.divergence = createTarget(simW, simH);399 this.curl = createTarget(simW, simH);400 this.passes = {401 splat: fluidPass(splatFragment, { uTarget: { value: null }, uAspect: { value: 1 }, uColor: { value: new THREE.Vector3() }, uPoint: { value: new THREE.Vector2() }, uRadius: { value: 0.001 } }),402 advect: fluidPass(advectFragment, { uVelocity: { value: null }, uSource: { value: null }, uDt: { value: 0 }, uDissipation: { value: 0 }, uTopSink: { value: 0 } }),403 curl: fluidPass(curlFragment, { uVelocity: { value: null } }),404 forces: fluidPass(forcesFragment, {405 uVelocity: { value: null },406 uCurl: { value: null },407 uDye: { value: null },408 uCurlStrength: { value: 24 },409 uDt: { value: 0 },410 uTime: { value: 0 },411 uTurbulence: { value: 0 },412 uNoiseScale: { value: 3 },413 uBuoyancy: { value: 0 },414 }),415 divergence: fluidPass(divergenceFragment, { uVelocity: { value: null } }),416 pressure: fluidPass(pressureFragment, { uPressure: { value: null }, uDivergence: { value: null } }),417 gradient: fluidPass(gradientFragment, { uPressure: { value: null }, uVelocity: { value: null } }),418 scale: fluidPass(scaleFragment, { uSource: { value: null }, uValue: { value: 0.8 } }),419 };420 this.mesh = new THREE.Mesh(this.geometry, this.passes.scale);421 this.mesh.frustumCulled = false;422 this.scene.add(this.mesh);423 }424425 get dyeTexture() {426 return this.dye.read.texture;427 }428429 get velocityTexture() {430 return this.velocity.read.texture;431 }432433 /** Draws a full-screen pass into `target` (null: the canvas). */434 render(material: THREE.ShaderMaterial, target: THREE.WebGLRenderTarget | null, texel: THREE.Vector2 = this.dyeTexel) {435 const texelUniform = material.uniforms.uTexel as THREE.IUniform<THREE.Vector2> | undefined;436 texelUniform?.value.copy(texel);437 this.mesh.material = material;438 this.gl.setRenderTarget(target);439 this.gl.render(this.scene, this.camera);440 }441442 /**443 * Adds force (dx, dy, in sim pixels per second) and dye at (x, y) in 0..1 canvas space. `radius`:444 * 0.1 (a needle) to 1 (a hand). A null color only pushes.445 */446 splat(x: number, y: number, dx: number, dy: number, color: SplatColor | null, strength: number, radius: number) {447 const s = this.passes.splat;448 const u = s.uniforms;449 u.uAspect.value = this.aspect;450 (u.uPoint.value as THREE.Vector2).set(x, y);451 u.uRadius.value = (0.0006 + radius * radius * 0.012) * (this.aspect > 1 ? 1 : 1 / this.aspect);452 u.uTarget.value = this.velocity.read.texture;453 (u.uColor.value as THREE.Vector3).set(dx, dy, 0);454 this.render(s, this.velocity.write, this.simTexel);455 this.velocity.swap();456 if (!color || strength <= 0) return;457 u.uTarget.value = this.dye.read.texture;458 (u.uColor.value as THREE.Vector3).set(color.r * strength, color.g * strength, color.b * strength);459 this.render(s, this.dye.write, this.dyeTexel);460 this.dye.swap();461 }462463 /** Moves the fluid forward by `step.dt` seconds. */464 step(step: FluidStep) {465 const { velocity, dye, pressure, divergence, curl, passes } = this;466 passes.curl.uniforms.uVelocity.value = velocity.read.texture;467 this.render(passes.curl, curl, this.simTexel);468469 const f = passes.forces.uniforms;470 f.uVelocity.value = velocity.read.texture;471 f.uCurl.value = curl.texture;472 f.uDye.value = dye.read.texture;473 f.uCurlStrength.value = step.curl ?? 24;474 f.uDt.value = step.dt;475 f.uTime.value = step.time;476 f.uTurbulence.value = step.turbulence ?? 0;477 f.uNoiseScale.value = step.noiseScale ?? 3;478 f.uBuoyancy.value = step.buoyancy ?? 0;479 this.render(passes.forces, velocity.write, this.simTexel);480 velocity.swap();481482 passes.divergence.uniforms.uVelocity.value = velocity.read.texture;483 this.render(passes.divergence, divergence, this.simTexel);484485 passes.scale.uniforms.uSource.value = pressure.read.texture;486 passes.scale.uniforms.uValue.value = 0.8;487 this.render(passes.scale, pressure.write, this.simTexel);488 pressure.swap();489 passes.pressure.uniforms.uDivergence.value = divergence.texture;490 for (let i = 0; i < this.iterations; i++) {491 passes.pressure.uniforms.uPressure.value = pressure.read.texture;492 this.render(passes.pressure, pressure.write, this.simTexel);493 pressure.swap();494 }495496 passes.gradient.uniforms.uPressure.value = pressure.read.texture;497 passes.gradient.uniforms.uVelocity.value = velocity.read.texture;498 this.render(passes.gradient, velocity.write, this.simTexel);499 velocity.swap();500501 const a = passes.advect.uniforms;502 a.uDt.value = step.dt;503 a.uVelocity.value = velocity.read.texture;504 a.uSource.value = velocity.read.texture;505 a.uDissipation.value = step.velocityDissipation;506 a.uTopSink.value = 0;507 this.render(passes.advect, velocity.write, this.simTexel);508 velocity.swap();509510 a.uVelocity.value = velocity.read.texture;511 a.uSource.value = dye.read.texture;512 a.uDissipation.value = step.dyeDissipation;513 a.uTopSink.value = step.topSink ?? 0;514 this.render(passes.advect, dye.write, this.simTexel);515 dye.swap();516 }517518 dispose() {519 this.velocity.dispose();520 this.dye.dispose();521 this.pressure.dispose();522 this.divergence.dispose();523 this.curl.dispose();524 Object.values(this.passes).forEach((m) => m.dispose());525 this.geometry.dispose();526 }527}528529/**530 * The solver for the current canvas. Rebuilt when the canvas is resized (the fluid restarts: rare,531 * and cheaper than resampling it) and disposed on unmount.532 */533function useFluidSolver(resolution: FluidResolution) {534 const gl = useThree((state) => state.gl);535 const width = useThree((state) => state.size.width);536 const height = useThree((state) => state.size.height);537 const { sim, dye, iterations } = resolution;538 const solver = useMemo(() => new FluidSolver(gl, width, height, { sim, dye, iterations }), [gl, width, height, sim, dye, iterations]);539 useEffect(() => () => solver.dispose(), [solver]);540 return solver;541}542543// The iridescent-oil fluid shared by FluidChromaWarp (a background) and FluidChromaCursor (a click-544// through overlay). Every push of the pointer is one stroke of ONE color, taken in order from the545// palette: the first push is drawn with the first color, the second with the second, and so on, then546// it loops. A push ends when the pointer rests for a moment, leaves, or is pressed again.547548const PUSH_PAUSE = 0.16; // s without movement that ends a push549550const MAX_COLORS = 8;551552// Final image: the dye as liquid metal (a normal from its gradient lights it), every color channel553// sampled a little apart along the flow (chromatic aberration). Transparent mode (the cursor) drops the554// ink and outputs straight alpha (the canvas must have premultipliedAlpha: false), so the page shows555// through everywhere the oil is not.556const displayFragment = /* glsl */ `557uniform sampler2D uDye;558uniform sampler2D uVelocity;559uniform vec2 uTexel;560uniform float uAberration;561uniform vec3 uBase;562uniform float uTransparent;563varying vec2 vUv;564vec3 dyeAt(vec2 uv) { return texture2D(uDye, uv).rgb; }565void main() {566 vec2 flow = texture2D(uVelocity, vUv).xy;567 // Split along the flow only where it moves: still oil stays clean, fast streaks fringe568 vec2 shift = clamp(flow * 0.00012, vec2(-0.004), vec2(0.004)) * uAberration;569 vec3 col = max(vec3(dyeAt(vUv + shift).r, dyeAt(vUv).g, dyeAt(vUv - shift).b), 0.0);570571 // Height = how much dye there is; its slope tilts a normal, lit like polished liquid metal572 float hL = length(dyeAt(vUv - vec2(uTexel.x, 0.0)));573 float hR = length(dyeAt(vUv + vec2(uTexel.x, 0.0)));574 float hT = length(dyeAt(vUv + vec2(0.0, uTexel.y)));575 float hB = length(dyeAt(vUv - vec2(0.0, uTexel.y)));576 vec3 n = normalize(vec3((hL - hR) * 3.0, (hB - hT) * 3.0, 1.0));577 vec3 light = normalize(vec3(-0.4, 0.6, 0.7));578 float spec = pow(max(dot(reflect(-light, n), vec3(0.0, 0.0, 1.0)), 0.0), 36.0);579 float rim = pow(1.0 - n.z, 2.0) * 2.0;580581 float amount = clamp(length(col) * 0.9, 0.0, 1.0);582 vec3 oil = col * (0.85 + rim) + vec3(spec) * amount * 1.6;583 if (uTransparent > 0.5) {584 // Straight (not premultiplied) alpha: the sRGB conversion below must apply to the color alone585 // Softer relief than on black ink: the fine normal detail would read as grain over a page586 vec3 color = 1.0 - exp(-(col * (0.9 + rim * 0.35) + vec3(spec) * amount * 0.7) * 1.35);587 // Opacity follows the amount of dye only (smooth), not the relief: no grain in thin, dark trails588 float alpha = clamp(max(max(col.r, col.g), col.b) * 1.8, 0.0, 1.0);589 gl_FragColor = vec4(min(color / max(alpha, 0.05), 1.0), alpha);590 } else {591 // Soft filmic roll-off: overlapping colors bloom instead of clipping592 gl_FragColor = vec4(1.0 - exp(-(uBase + oil) * 1.35), 1.0);593 }594 #include <colorspace_fragment>595}596`;597598interface ChromaFluidProps {599 /** Color of each push, in order (1 to 8, then it loops). */600 colors: readonly string[];601 /** 0 (thin, fades fast) to 1 (thick oil, lingers). */602 viscosity: number;603 /** 0 to 1. */604 aberration: number;605 /** Size of the push, 0.1 (a needle) to 1 (a hand). */606 radius: number;607 /** Idle swirl of the surface, 0 to 2 (and, with `ambient`, how often idle drops fall). */608 turbulence: number;609 /** Ink color under the oil (ignored when transparent). */610 baseColor: string;611 /** Clear canvas: only the oil is drawn (cursor overlay). */612 transparent: boolean;613 /** Idle drops of color, in palette order, at fixed spots: the surface never rests empty. */614 ambient: boolean;615 /** Reduced motion: the fluid stays still (pushes still draw). */616 still: boolean;617 lowPowerMode: boolean;618}619620/** Spreads 0, 1, 2, … evenly over the canvas (golden-ratio sequence): fixed spots, no randomness. */621function spot(k: number) {622 return { x: 0.15 + 0.7 * ((k * 0.618034 + 0.31) % 1), y: 0.15 + 0.7 * ((k * 0.414214 + 0.57) % 1), angle: k * 2.39996 };623}624625const ChromaFluid = memo(function ChromaFluid({ colors, viscosity, aberration, radius, turbulence, baseColor, transparent, ambient, still, lowPowerMode }: ChromaFluidProps) {626 const resolution = useMemo<FluidResolution>(() => (lowPowerMode ? { sim: 96, dye: 384, iterations: 14 } : { sim: 144, dye: 768, iterations: 22 }), [lowPowerMode]);627 const solver = useFluidSolver(resolution);628 const push = useRef({ index: -1, lastMove: -Infinity, newPush: true, ambient: 0, ambientCount: 0, seeded: false, x: 0, y: 0, ready: false });629 const pointer = useCanvasPointer(() => {630 push.current.newPush = true;631 });632633 const display = useMemo(634 () =>635 fluidPass(636 displayFragment,637 { uDye: { value: null }, uVelocity: { value: null }, uAberration: { value: 0 }, uBase: { value: new THREE.Color() }, uTransparent: { value: 0 } },638 { transparent: true, blending: THREE.NoBlending }639 ),640 []641 );642 useEffect(() => () => display.dispose(), [display]);643 useEffect(() => {644 (display.uniforms.uBase.value as THREE.Color).set(baseColor);645 display.uniforms.uTransparent.value = transparent ? 1 : 0;646 }, [display, baseColor, transparent]);647648 const paletteKey = colors.slice(0, MAX_COLORS).join(",");649 const palette = useMemo(() => (paletteKey ? paletteKey.split(",") : ["#ffffff"]).map((c) => new THREE.Color(c)), [paletteKey]);650651 // A new solver (first mount, resize) starts empty: seed it again, and restart the color sequence652 useEffect(() => {653 push.current.seeded = false;654 push.current.index = -1;655 push.current.ambientCount = 0;656 }, [solver]);657658 useFrame((state, delta) => {659 const dt = Math.min(delta, 1 / 30);660 const now = state.clock.elapsedTime;661 const s = push.current;662 const v = THREE.MathUtils.clamp(viscosity, 0, 1);663664 // The background starts with a few swirls already in the ink, one per palette color in order665 if (!s.seeded) {666 s.seeded = true;667 if (ambient) {668 for (let k = 0; k < 7; k++) {669 const at = spot(k);670 solver.splat(at.x, at.y, Math.cos(at.angle) * 900, Math.sin(at.angle) * 900, palette[k % palette.length], 0.35, radius);671 }672 s.ambientCount = 7;673 }674 }675676 // Pointer: force along its motion, dye in the color of the current push677 const p = pointer.current;678 const x = p.ndc.x * 0.5 + 0.5;679 const y = p.ndc.y * 0.5 + 0.5;680 if (p.inside && s.ready) {681 const dx = (x - s.x) * 6000;682 const dy = (y - s.y) * 6000;683 const moved = Math.hypot(dx, dy);684 if (moved > 1) {685 if (s.newPush || now - s.lastMove > PUSH_PAUSE) {686 s.index = (s.index + 1) % palette.length;687 s.newPush = false;688 }689 s.lastMove = now;690 solver.splat(x, y, dx, dy, palette[Math.max(s.index, 0)], Math.min(moved / 900, 1.4) * 0.55, radius);691 }692 } else if (!p.inside) {693 s.newPush = true;694 }695 s.x = x;696 s.y = y;697 s.ready = p.inside;698699 // At rest the surface keeps breathing: soft drops at fixed spots, colors in palette order700 s.ambient -= dt;701 if (ambient && !still && turbulence > 0 && s.ambient <= 0) {702 s.ambient = 0.9 / Math.max(turbulence, 0.2);703 const k = s.ambientCount++;704 const at = spot(k);705 solver.splat(at.x, at.y, Math.cos(at.angle) * 420 * turbulence, Math.sin(at.angle) * 420 * turbulence, palette[k % palette.length], 0.22, radius);706 }707708 if (!still) {709 solver.step({710 dt,711 time: now,712 velocityDissipation: THREE.MathUtils.lerp(1.6, 0.12, v),713 dyeDissipation: THREE.MathUtils.lerp(1.1, 0.18, v),714 turbulence,715 });716 }717718 const d = display.uniforms;719 d.uDye.value = solver.dyeTexture;720 d.uVelocity.value = solver.velocityTexture;721 d.uAberration.value = aberration * 1.6;722 solver.render(display, null);723 }, 1);724725 return null;726});727728export interface FluidChromaCursorProps extends Pick<PerformanceProps, "lowPowerMode" | "respectReducedMotion"> {729 /**730 * Color of each push, in order (1 to 8 colors): the first push of the pointer is drawn in the first731 * color, the next one in the second, and so on, then it loops. A push ends when the pointer rests for732 * a moment, leaves the window, or is pressed. Never random. Default violet, cyan, magenta, gold.733 */734 colorPalette?: readonly string[];735 /** How long the trail lingers, 0 (thin, fades fast) to 1 (thick oil). Default 0.3. */736 fluidViscosity?: number;737 /** Spectral split of the color channels along the flow, 0 to 1. Default 0.5. */738 chromaticAberration?: number;739 /** Size of the trail, 0.1 (a needle) to 1 (a hand). Default 0.25. */740 cursorInfluenceRadius?: number;741 /** How much the trail keeps swirling once left behind, 0 (still) to 2. Default 0.35. */742 waveTurbulence?: number;743 /** Hide the system cursor. Default false. */744 hideNativeCursor?: boolean;745}746747const DEFAULT_PALETTE = ["#7c3aed", "#22d3ee", "#ec4899", "#f5b94a"] as const;748749/**750 * The Fluid Chroma Warp effect as a cursor: the pointer drags a trail of iridescent liquid oil over the751 * page, each push in the next color of the palette, swirling and fading behind it. A transparent,752 * click-through WebGL layer above the whole viewport; off on touch screens.753 */754function FluidChromaCursor({755 colorPalette = DEFAULT_PALETTE,756 fluidViscosity = 0.3,757 chromaticAberration = 0.5,758 cursorInfluenceRadius = 0.25,759 waveTurbulence = 0.35,760 hideNativeCursor = false,761 respectReducedMotion = true,762 lowPowerMode = false,763}: FluidChromaCursorProps) {764 const enabled = useCursorEnabled();765 const reduced = usePrefersReducedMotion();766 useHideNativeCursor(enabled && hideNativeCursor);767 if (!enabled) return null;768769 return (770 <div style={OVERLAY_STYLE} aria-hidden="true">771 <Canvas772 dpr={lowPowerMode ? 1 : [1, 1.5]}773 gl={{ antialias: false, alpha: true, premultipliedAlpha: false, powerPreference: "high-performance" }}774 style={{ pointerEvents: "none" }}775 >776 <ChromaFluid777 colors={colorPalette}778 viscosity={fluidViscosity}779 aberration={chromaticAberration}780 radius={cursorInfluenceRadius}781 turbulence={waveTurbulence}782 baseColor="#000000"783 transparent784 ambient={false}785 still={respectReducedMotion && reduced}786 lowPowerMode={lowPowerMode}787 />788 </Canvas>789 </div>790 );791}792793export default memo(FluidChromaCursor);
03
Drop it in a page
Updated live with the settings above.
app/page.tsx
1import FluidChromaCursor from "@/components/FluidChromaCursor";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 <FluidChromaCursor8 fluidViscosity={0.3}9 chromaticAberration={0.5}10 cursorInfluenceRadius={0.25}11 waveTurbulence={0.35}12 colorPalette={["#7c3aed", "#22d3ee", "#ec4899", "#f5b94a"]}13 hideNativeCursor={false}14 />15 </div>16 );17}