Loading…
← All components

Cursors · Cursor

Ribbon Cursor

A glowing ribbon that trails behind the pointer and fades once it stops.

Hover this linkdata-cursor-hover
<CursorRibbon3D />Live

Customize

Color#a5b4fc

Installation

Use it in your project

Or skip the copy-paste

One command: writes the file and installs the dependencies.

$ npx deepui-cli add cursor-ribbon
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/CursorRibbon3D.tsx and paste it in.

components/CursorRibbon3D.tsx
1"use client";
2
3import {
4 memo,
5 useEffect,
6 useLayoutEffect,
7 useMemo,
8 useRef,
9 useState,
10 type CSSProperties,
11 type ReactNode,
12} from "react";
13import * as THREE from "three";
14import { Canvas, useFrame, useThree, type CanvasProps } from "@react-three/fiber";
15
16/**
17 * The shared props API of DeepUI's individual 3D components (not the full-page templates, which keep
18 * their own tailored scenes).
19 *
20 * The props are grouped by concern. A component extends ONLY the groups it really applies, so its
21 * 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 are
27 * inlined into each component's single-file bundle (lib/bundle-source.mjs), only what it uses.
28 */
29
30/** 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";
32
33/** 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}
44
45/** 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}
56
57/** 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}
70
71/** 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}
88
89/** 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}
100
101/** 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}
110
111/** 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}
120
121/** Every group at once. Components extend only the groups they apply (see the top of this file). */
122interface Base3DComponentProps
123 extends CursorProps,
124 TiltProps,
125 Text3DProps,
126 MaterialProps,
127 MotionProps,
128 EnvironmentProps,
129 PerformanceProps {}
130
131type Defaults = Required<Omit<Base3DComponentProps, "text" | "fontUrl" | "particleCount" | "cameraFov">>;
132
133/** 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};
162
163/** Inline widget: fills its positioned parent and receives pointer events. */
164const FILL_STYLE: CSSProperties = { position: "absolute", top: 0, left: 0, width: "100%", height: "100%" };
165
166/** Cursor overlay: covers the viewport, above everything, never intercepts the page's events. */
167const OVERLAY_STYLE: CSSProperties = {
168 position: "fixed",
169 top: 0,
170 left: 0,
171 width: "100%",
172 height: "100%",
173 pointerEvents: "none",
174 zIndex: 9999,
175};
176
177interface UICanvasProps extends Omit<CanvasProps, "children" | "style" | "gl">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {
178 children: ReactNode;
179 /** Full-viewport, click-through overlay (cursors) instead of an inline widget. */
180 overlay?: boolean;
181}
182
183/**
184 * Ready-to-use <Canvas>: pauses its render loop while scrolled out of view (pauseWhenOffscreen), pixel
185 * ratio 1 in lowPowerMode; R3F disposes the renderer and its WebGL context on unmount.
186 */
187function UICanvas({ children, overlay = false, dpr = [1, 2], pauseWhenOffscreen = DEFAULT_3D_PROPS.pauseWhenOffscreen, lowPowerMode = DEFAULT_3D_PROPS.lowPowerMode, ...canvasProps }: UICanvasProps) {
188 const containerRef = useRef<HTMLDivElement>(null);
189 // In view at first: the first frame is always drawn before the loop can be paused
190 const [inView, setInView] = useState(true);
191 useEffect(() => {
192 const el = containerRef.current;
193 if (!el || !pauseWhenOffscreen) return undefined;
194 const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting));
195 observer.observe(el);
196 return () => observer.disconnect();
197 }, [pauseWhenOffscreen]);
198 return (
199 <div ref={containerRef} style={overlay ? OVERLAY_STYLE : FILL_STYLE} aria-hidden="true">
200 <Canvas
201 dpr={lowPowerMode ? 1 : dpr}
202 frameloop={inView || !pauseWhenOffscreen ? "always" : "never"}
203 gl={{ antialias: true, alpha: true, powerPreference: "high-performance" }}
204 style={overlay ? { pointerEvents: "none" } : undefined}
205 {...canvasProps}
206 >
207 {children}
208 </Canvas>
209 </div>
210 );
211}
212
213/**
214 * Perspective camera placed so that 1 world unit = 1 CSS pixel on the z = 0 plane: widgets are laid
215 * out in pixels like the rest of the page, and still get real depth (presses, tilts, shadows).
216 */
217function PixelPerspective({ fov = 30 }: { fov?: number }) {
218 const camera = useThree((state) => state.camera) as THREE.PerspectiveCamera;
219 const size = useThree((state) => state.size);
220 useLayoutEffect(() => {
221 camera.fov = fov;
222 camera.near = 1;
223 camera.far = 20000;
224 camera.position.set(0, 0, size.height / 2 / Math.tan(THREE.MathUtils.degToRad(fov / 2)));
225 camera.lookAt(0, 0, 0);
226 camera.updateProjectionMatrix();
227 }, [camera, size, fov]);
228 return null;
229}
230
231/** True on devices with a precise pointer (mouse, trackpad): cursors make no sense on touch screens. */
232function useFinePointer() {
233 const [fine, setFine] = useState(false);
234 useEffect(() => {
235 const query = window.matchMedia("(pointer: fine)");
236 const sync = () => setFine(query.matches);
237 sync();
238 query.addEventListener("change", sync);
239 return () => query.removeEventListener("change", sync);
240 }, []);
241 return fine;
242}
243
244export interface CursorRibbonProps extends Pick<MaterialProps, "primaryColor">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {
245 primaryColor?: string;
246 /** @deprecated Use `primaryColor`. */
247 color?: string;
248 /** Width of the ribbon at the pointer, in CSS pixels. Default 14. */
249 lineWidth?: number;
250 /** Number of control points in the trail: longer = more ribbon. Default 40. */
251 trailLength?: number;
252 /** How fast the trail catches up and fades once the pointer stops. Default 1. */
253 decaySpeed?: number;
254}
255
256const SAMPLES_PER_POINT = 3; // Catmull-Rom samples between two control points
257
258const ribbonVertexShader = /* glsl */ `
259attribute float aT; // 0 at the pointer → 1 at the tail
260attribute float aSide; // -1 / +1 across the ribbon
261varying float vT;
262varying float vSide;
263void main() {
264 vT = aT;
265 vSide = aSide;
266 gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
267}
268`;
269
270const ribbonFragmentShader = /* glsl */ `
271uniform vec3 uColor;
272uniform float uActivity;
273uniform float uCore; // how much the center line burns white
274varying float vT;
275varying float vSide;
276void main() {
277 float across = 1.0 - abs(vSide);
278 float body = smoothstep(0.0, 0.8, across);
279 float core = pow(across, 6.0);
280 float fade = pow(1.0 - vT, 1.6) * uActivity;
281 vec3 color = mix(uColor, vec3(1.0), core * uCore);
282 gl_FragColor = vec4(color, (body * 0.75 + core * 0.5) * fade);
283 #include <colorspace_fragment>
284}
285`;
286
287interface Strip {
288 geometry: THREE.BufferGeometry;
289 positions: Float32Array;
290}
291
292/** Triangle strip with two vertices per sample; positions are rewritten every frame. */
293function createStrip(samples: number): Strip {
294 const positions = new Float32Array(samples * 2 * 3);
295 const t = new Float32Array(samples * 2);
296 const side = new Float32Array(samples * 2);
297 const indices: number[] = [];
298 for (let k = 0; k < samples; k++) {
299 t[k * 2] = t[k * 2 + 1] = k / (samples - 1);
300 side[k * 2] = -1;
301 side[k * 2 + 1] = 1;
302 if (k < samples - 1) {
303 const a = k * 2;
304 indices.push(a, a + 1, a + 2, a + 1, a + 3, a + 2);
305 }
306 }
307 const geometry = new THREE.BufferGeometry();
308 geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3).setUsage(THREE.DynamicDrawUsage));
309 geometry.setAttribute("aT", new THREE.BufferAttribute(t, 1));
310 geometry.setAttribute("aSide", new THREE.BufferAttribute(side, 1));
311 geometry.setIndex(indices);
312 return { geometry, positions };
313}
314
315function createRibbonMaterial(core: number) {
316 return new THREE.ShaderMaterial({
317 uniforms: { uColor: { value: new THREE.Color() }, uActivity: { value: 0 }, uCore: { value: core } },
318 vertexShader: ribbonVertexShader,
319 fragmentShader: ribbonFragmentShader,
320 transparent: true,
321 depthWrite: false,
322 depthTest: false,
323 blending: THREE.AdditiveBlending,
324 side: THREE.DoubleSide,
325 });
326}
327
328/** The trail itself, for an existing R3F scene. It reads the pointer from the window. */
329export const CursorRibbonScene = memo(function CursorRibbonScene({
330 primaryColor,
331 color = primaryColor ?? "#a5b4fc",
332 lineWidth = 14,
333 trailLength = 40,
334 decaySpeed = 1,
335}: CursorRibbonProps) {
336 const gl = useThree((state) => state.gl);
337 const count = Math.max(4, Math.round(trailLength));
338 const sampleCount = count * SAMPLES_PER_POINT;
339 const pointer = useRef({ x: 0, y: 0, inside: false, seen: false, lastMove: -Infinity });
340 const activity = useRef(0);
341
342 // Control points (followed in a chain) and a Catmull-Rom curve through them, sampled into the strips
343 const trail = useMemo(() => {
344 const points = Array.from({ length: count }, () => new THREE.Vector3());
345 const curve = new THREE.CatmullRomCurve3(points, false, "centripetal");
346 const samples = Array.from({ length: sampleCount }, () => new THREE.Vector3());
347 return { points, curve, samples, started: false };
348 }, [count, sampleCount]);
349
350 const ribbon = useMemo(() => createStrip(sampleCount), [sampleCount]);
351 const strand = useMemo(() => createStrip(sampleCount), [sampleCount]);
352 const ribbonMaterial = useMemo(() => createRibbonMaterial(0.55), []);
353 const strandMaterial = useMemo(() => createRibbonMaterial(1), []);
354 const scratch = useMemo(() => ({ ndc: new THREE.Vector3(), direction: new THREE.Vector3(), head: new THREE.Vector3() }), []);
355
356 useEffect(() => {
357 (ribbonMaterial.uniforms.uColor.value as THREE.Color).set(color);
358 (strandMaterial.uniforms.uColor.value as THREE.Color).set(color).lerp(new THREE.Color(1, 1, 1), 0.5);
359 }, [ribbonMaterial, strandMaterial, color]);
360 useEffect(
361 () => () => {
362 ribbon.geometry.dispose();
363 strand.geometry.dispose();
364 },
365 [ribbon, strand]
366 );
367 useEffect(
368 () => () => {
369 ribbonMaterial.dispose();
370 strandMaterial.dispose();
371 },
372 [ribbonMaterial, strandMaterial]
373 );
374
375 useEffect(() => {
376 const el = gl.domElement;
377 const move = (event: PointerEvent) => {
378 const rect = el.getBoundingClientRect();
379 const p = pointer.current;
380 p.x = event.clientX - rect.left;
381 p.y = event.clientY - rect.top;
382 p.inside = p.x >= 0 && p.y >= 0 && p.x <= rect.width && p.y <= rect.height;
383 p.seen = true;
384 p.lastMove = performance.now();
385 };
386 window.addEventListener("pointermove", move, { passive: true });
387 return () => window.removeEventListener("pointermove", move);
388 }, [gl]);
389
390 useFrame((state, delta) => {
391 const dt = Math.min(delta, 1 / 30);
392 const p = pointer.current;
393 if (!p.seen) return;
394 const { camera, size } = state;
395
396 // Head = pointer on the z = 0 plane
397 scratch.ndc.set((p.x / size.width) * 2 - 1, -(p.y / size.height) * 2 + 1, 0.5).unproject(camera);
398 scratch.direction.copy(scratch.ndc).sub(camera.position).normalize();
399 scratch.head.copy(camera.position).addScaledVector(scratch.direction, -camera.position.z / scratch.direction.z);
400
401 const { points, curve, samples } = trail;
402 if (!trail.started) {
403 points.forEach((point) => point.copy(scratch.head));
404 trail.started = true;
405 }
406 // Each point chases the one ahead of it: a fluid trail that shrinks back to the pointer when it stops
407 points[0].copy(scratch.head);
408 const follow = 1 - Math.exp(-22 * decaySpeed * dt);
409 for (let i = 1; i < points.length; i++) points[i].lerp(points[i - 1], follow);
410
411 // Fades out a moment after the pointer stops or leaves
412 const idle = (performance.now() - p.lastMove) / 1000;
413 const targetActivity = p.inside && idle < 0.35 / decaySpeed ? 1 : 0;
414 activity.current = THREE.MathUtils.damp(activity.current, targetActivity, targetActivity ? 12 : 3 * decaySpeed, dt);
415 ribbonMaterial.uniforms.uActivity.value = activity.current;
416 strandMaterial.uniforms.uActivity.value = activity.current;
417
418 for (let k = 0; k < samples.length; k++) curve.getPoint(k / (samples.length - 1), samples[k]);
419
420 const worldPerPixel = state.viewport.getCurrentViewport(camera, [0, 0, 0]).width / size.width;
421 const halfWidth = (lineWidth * worldPerPixel) / 2;
422 const time = state.clock.elapsedTime;
423 for (let k = 0; k < samples.length; k++) {
424 const prev = samples[Math.max(0, k - 1)];
425 const next = samples[Math.min(samples.length - 1, k + 1)];
426 let tx = next.x - prev.x;
427 let ty = next.y - prev.y;
428 const len = Math.hypot(tx, ty) || 1;
429 tx /= len;
430 ty /= len;
431 // Normal in the screen plane
432 const nx = -ty;
433 const ny = tx;
434 const t = k / (samples.length - 1);
435 const s = samples[k];
436
437 // Main ribbon: tapers towards the tail
438 const w = halfWidth * Math.pow(1 - t, 0.8);
439 const o = k * 6;
440 ribbon.positions[o] = s.x - nx * w;
441 ribbon.positions[o + 1] = s.y - ny * w;
442 ribbon.positions[o + 2] = s.z;
443 ribbon.positions[o + 3] = s.x + nx * w;
444 ribbon.positions[o + 4] = s.y + ny * w;
445 ribbon.positions[o + 5] = s.z;
446
447 // Thin bright strand winding around the ribbon's path
448 const wind = Math.sin(t * 22 - time * 9) * halfWidth * 1.1 * (1 - t);
449 const sw = halfWidth * 0.18 * (1 - t);
450 const cx = s.x + nx * wind;
451 const cy = s.y + ny * wind;
452 strand.positions[o] = cx - nx * sw;
453 strand.positions[o + 1] = cy - ny * sw;
454 strand.positions[o + 2] = s.z;
455 strand.positions[o + 3] = cx + nx * sw;
456 strand.positions[o + 4] = cy + ny * sw;
457 strand.positions[o + 5] = s.z;
458 }
459 (ribbon.geometry.attributes.position as THREE.BufferAttribute).needsUpdate = true;
460 (strand.geometry.attributes.position as THREE.BufferAttribute).needsUpdate = true;
461 });
462
463 return (
464 <>
465 <mesh geometry={ribbon.geometry} material={ribbonMaterial} frustumCulled={false} renderOrder={10} />
466 <mesh geometry={strand.geometry} material={strandMaterial} frustumCulled={false} renderOrder={11} />
467 </>
468 );
469});
470
471/** Self-contained trail: a full-viewport, click-through overlay canvas. Render it once, e.g. in the layout. */
472function CursorRibbon3D(props: CursorRibbonProps) {
473 const finePointer = useFinePointer();
474 if (!finePointer) return null;
475 return (
476 <UICanvas pauseWhenOffscreen={props.pauseWhenOffscreen} lowPowerMode={props.lowPowerMode} overlay>
477 <PixelPerspective />
478 <CursorRibbonScene {...props} />
479 </UICanvas>
480 );
481}
482
483export default memo(CursorRibbon3D);
03

Drop it in a page

Updated live with the settings above.

app/page.tsx
1import CursorRibbon3D from "@/components/CursorRibbon3D";
2
3export default function Section() {
4 return (
5 // The component fills this box: give it a position and a height
6 <div style={{ position: "relative", width: "100%", height: "100vh" }}>
7 <CursorRibbon3D
8 lineWidth={14}
9 trailLength={40}
10 decaySpeed={1}
11 primaryColor="#a5b4fc"
12 />
13 </div>
14 );
15}
Next componentGlass Navbar→