Loading…
← All components

Typography · Ribbon

Moebius Ribbon

Your text scrolling forever along a Möbius strip slowly turning in space, gliding from one face onto the other.

<MoebiusRibbonText3D />Live

Customize

Ribbon#111114
Text#f4f4f5

Installation

Use it in your project

Or skip the copy-paste

One command: writes the file and installs the dependencies.

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

components/MoebiusRibbonText3D.tsx
1"use client";
2
3import {
4 Component,
5 memo,
6 Suspense,
7 useEffect,
8 useLayoutEffect,
9 useMemo,
10 useRef,
11 useState,
12 type CSSProperties,
13 type ReactNode,
14 type RefObject,
15} from "react";
16import * as THREE from "three";
17import { Canvas, useFrame, useThree, type CanvasProps } from "@react-three/fiber";
18
19/**
20 * The shared props API of DeepUI's individual 3D components (not the full-page templates, which keep
21 * their own tailored scenes).
22 *
23 * The props are grouped by concern. A component extends ONLY the groups it really applies, so its
24 * type never advertises a knob that does nothing (a card has no particles, a background has no tilt):
25 *
26 * interface MyCardProps extends CursorProps, TiltProps, MaterialProps, PerformanceProps { … }
27 *
28 * `Base3DComponentProps` is every group at once, for tooling that handles any component. Same name,
29 * same unit and same meaning everywhere; the default values live in DEFAULT_3D_PROPS. These files are
30 * inlined into each component's single-file bundle (lib/bundle-source.mjs), only what it uses.
31 */
32
33/** Which rotation axes follow the pointer. "x-only": the object nods (up / down); "y-only": it turns (left / right). */
34export type TiltAxis = "both" | "x-only" | "y-only" | "none";
35
36/** 1. Cursor: how the pointer pulls, pushes and drags the object. */
37interface CursorProps {
38 /** 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). */
39 cursorRadius?: number;
40 /** Positive pulls things towards the pointer, negative pushes them away (repulsion, shockwave). Default 1. */
41 cursorForce?: number;
42 /** How far the object slides towards the pointer, 0 (stays put) to 1 (follows closely). Default 0. */
43 magneticStrength?: number;
44 /** Share of the remaining distance the motion closes each frame (at 60 fps), 0.01 (heavy, slow) to 1 (instant). Default 0.1. */
45 cursorDamping?: number;
46}
47
48/** 2. Tilt and parallax: the object leans towards the pointer, its layers slide against each other. */
49interface TiltProps {
50 /** Largest lean towards the pointer, in degrees. Default 15. */
51 maxTiltAngle?: number;
52 /** Axes that follow the pointer. Default "both". */
53 tiltAxis?: TiltAxis;
54 /** Lean away from the pointer instead of towards it. Default false. */
55 invertTilt?: boolean;
56 /** How far apart the depth layers slide when the object tilts, 0 (flat) to 2. Default 1. */
57 parallaxOffset?: number;
58}
59
60/** 3. Text and 3D typography, for components that draw a label. */
61interface Text3DProps {
62 /** The label drawn by the component. */
63 text?: string;
64 /** Scale of the lettering. Default 1. */
65 fontSize?: number;
66 /** Extrusion depth of 3D letters. Default 0.2. */
67 textDepth?: number;
68 /** Bevelled, light-catching edges on 3D letters. Default true. */
69 bevelEnabled?: boolean;
70 /** Custom font: a .woff / .ttf (flat text) or a typeface .json (extruded text). */
71 fontUrl?: string;
72}
73
74/** 4. Rendering, materials and glow. */
75interface MaterialProps {
76 /** Main color of the object. Default "#6366f1". */
77 primaryColor?: string;
78 /** Color of the glow. Default "#00f0ff". */
79 emissiveColor?: string;
80 /** Strength of the glow, 0 (none) to 3. Default 1. */
81 emissiveIntensity?: number;
82 /** 0 (mirror, glass) to 1 (matte). Default 0.3. */
83 roughness?: number;
84 /** 0 (plastic, organic) to 1 (metal). Default 0.5. */
85 metalness?: number;
86 /** 0 (opaque) to 1 (clear glass): see-through, refracting surfaces. Default 0. */
87 transmission?: number;
88 /** Technical wireframe rendering. Default false. */
89 wireframe?: boolean;
90}
91
92/** 5. Particles, idle motion and shader animation. */
93interface MotionProps {
94 /** Number of instanced elements. Default depends on the component. */
95 particleCount?: number;
96 /** Spin on its own, in radians per second (negative: the other way; 0.5 ≈ one turn in 12 s). Default 0. */
97 autoRotateSpeed?: number;
98 /** Pulses or ripples per second. Default 1. */
99 pulseRate?: number;
100 /** Amplitude of the noise deformation, 0 (none) to 2. Default 1. */
101 displacementScale?: number;
102}
103
104/** 6. Environment and camera. */
105interface EnvironmentProps {
106 /** Camera field of view, in degrees. Default depends on the component. */
107 cameraFov?: number;
108 /** Color of the depth fog. Default "#0a0a0a". */
109 fogColor?: string;
110 /** Thickness of the fog, 0 (none) to 0.2. Default 0. */
111 fogDensity?: number;
112}
113
114/** 7. Performance and accessibility. */
115interface PerformanceProps {
116 /** Lighter rendering for weak devices: pixel ratio 1, fewer instances, smaller environment maps. Default false. */
117 lowPowerMode?: boolean;
118 /** Under the OS "reduce motion" setting, stop idle spin, pulses and deformation (pointer feedback stays). Default true. */
119 respectReducedMotion?: boolean;
120 /** Stop the render loop while the component is scrolled out of view. Default true. */
121 pauseWhenOffscreen?: boolean;
122}
123
124/** Every group at once. Components extend only the groups they apply (see the top of this file). */
125interface Base3DComponentProps
126 extends CursorProps,
127 TiltProps,
128 Text3DProps,
129 MaterialProps,
130 MotionProps,
131 EnvironmentProps,
132 PerformanceProps {}
133
134type Defaults = Required<Omit<Base3DComponentProps, "text" | "fontUrl" | "particleCount" | "cameraFov">>;
135
136/** The values a prop takes when it is left out. A component may override one, and then documents it. */
137const DEFAULT_3D_PROPS: Defaults = {
138 cursorRadius: 220,
139 cursorForce: 1,
140 magneticStrength: 0,
141 cursorDamping: 0.1,
142 maxTiltAngle: 15,
143 tiltAxis: "both",
144 invertTilt: false,
145 parallaxOffset: 1,
146 fontSize: 1,
147 textDepth: 0.2,
148 bevelEnabled: true,
149 primaryColor: "#6366f1",
150 emissiveColor: "#00f0ff",
151 emissiveIntensity: 1,
152 roughness: 0.3,
153 metalness: 0.5,
154 transmission: 0,
155 wireframe: false,
156 autoRotateSpeed: 0,
157 pulseRate: 1,
158 displacementScale: 1,
159 fogColor: "#0a0a0a",
160 fogDensity: 0,
161 lowPowerMode: false,
162 respectReducedMotion: true,
163 pauseWhenOffscreen: true,
164};
165
166/** Fills the positioned parent and receives pointer events. */
167const FILL_STYLE: CSSProperties = { position: "absolute", top: 0, left: 0, width: "100%", height: "100%" };
168
169/** Visually hidden but read by screen readers (the canvas itself is aria-hidden). */
170const SR_ONLY: CSSProperties = {
171 position: "absolute",
172 width: 1,
173 height: 1,
174 padding: 0,
175 margin: -1,
176 overflow: "hidden",
177 clip: "rect(0, 0, 0, 0)",
178 whiteSpace: "nowrap",
179 border: 0,
180};
181
182interface TypeCanvasProps extends Omit<CanvasProps, "children" | "style" | "frameloop" | "gl">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {
183 children: ReactNode;
184 /** The text, for screen readers. */
185 label: string;
186 /** HTML laid over the canvas (controls…). */
187 overlay?: ReactNode;
188}
189
190/**
191 * Ready-to-use <Canvas> shared by the typography components: fills its positioned parent, pauses
192 * its render loop while scrolled out of view, exposes the text to screen readers, and R3F disposes
193 * the renderer and its WebGL context on unmount. A font that fails to load leaves an empty canvas.
194 */
195function TypeCanvas({ children, label, overlay, dpr = [1, 2], pauseWhenOffscreen = DEFAULT_3D_PROPS.pauseWhenOffscreen, lowPowerMode = DEFAULT_3D_PROPS.lowPowerMode, ...canvasProps }: TypeCanvasProps) {
196 const containerRef = useRef<HTMLDivElement>(null);
197 const [inView, setInView] = useState(true);
198
199 useEffect(() => {
200 const el = containerRef.current;
201 if (!el) return undefined;
202 const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting));
203 observer.observe(el);
204 return () => observer.disconnect();
205 }, []);
206
207 return (
208 <div ref={containerRef} style={FILL_STYLE}>
209 <span style={SR_ONLY}>{label}</span>
210 <Canvas
211 aria-hidden="true"
212 dpr={lowPowerMode ? 1 : dpr}
213 frameloop={inView || !pauseWhenOffscreen ? "always" : "never"}
214 gl={{ antialias: true, alpha: true, powerPreference: "high-performance" }}
215 style={{ touchAction: "pan-y" }}
216 {...canvasProps}
217 >
218 <SceneBoundary>
219 <Suspense fallback={null}>{children}</Suspense>
220 </SceneBoundary>
221 </Canvas>
222 {overlay}
223 </div>
224 );
225}
226
227class SceneBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {
228 state = { failed: false };
229 static getDerivedStateFromError() {
230 return { failed: true };
231 }
232 render() {
233 return this.state.failed ? null : this.props.children;
234 }
235}
236
237function usePrefersReducedMotion() {
238 const [reduced, setReduced] = useState(false);
239 useEffect(() => {
240 const query = window.matchMedia("(prefers-reduced-motion: reduce)");
241 const sync = () => setReduced(query.matches);
242 sync();
243 query.addEventListener("change", sync);
244 return () => query.removeEventListener("change", sync);
245 }, []);
246 return reduced;
247}
248
249interface CanvasPointer {
250 /** Pointer position in normalized device coordinates of the canvas (-1..1). */
251 ndc: THREE.Vector2;
252 /** True while the pointer is over the canvas. */
253 inside: boolean;
254 /** Pointer speed, in NDC units per second (smoothed). */
255 speed: number;
256}
257
258/**
259 * Tracks the pointer relative to the canvas through window listeners, so HTML laid over the canvas
260 * never blocks it. Returns a ref read inside useFrame: pointer moves never re-render React.
261 */
262function useCanvasPointer(): RefObject<CanvasPointer> {
263 const gl = useThree((state) => state.gl);
264 const pointer = useRef<CanvasPointer>({ ndc: new THREE.Vector2(), inside: false, speed: 0 });
265
266 useEffect(() => {
267 const el = gl.domElement;
268 let lastTime = performance.now();
269 const move = (event: PointerEvent) => {
270 const rect = el.getBoundingClientRect();
271 const p = pointer.current;
272 const x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
273 const y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
274 const now = performance.now();
275 const dt = Math.max(1, now - lastTime) / 1000;
276 lastTime = now;
277 p.speed = p.speed * 0.7 + (Math.hypot(x - p.ndc.x, y - p.ndc.y) / dt) * 0.3;
278 p.ndc.set(x, y);
279 p.inside = Math.abs(x) <= 1 && Math.abs(y) <= 1;
280 };
281 const leave = () => {
282 pointer.current.inside = false;
283 };
284 window.addEventListener("pointermove", move, { passive: true });
285 document.documentElement.addEventListener("pointerleave", leave);
286 window.addEventListener("blur", leave);
287 return () => {
288 window.removeEventListener("pointermove", move);
289 document.documentElement.removeEventListener("pointerleave", leave);
290 window.removeEventListener("blur", leave);
291 };
292 }, [gl]);
293
294 return pointer;
295}
296
297interface FitToViewProps {
298 children: ReactNode;
299 /** Size of the content in world units, at scale 1. Measured from the children when omitted. */
300 size?: [number, number];
301 /** Largest share of the view width the content may take. Default 0.86. */
302 maxWidth?: number;
303 /** Largest share of the view height the content may take. Default 0.62. */
304 maxHeight?: number;
305 /** Changes when the content changes, to measure it again. */
306 measureKey?: unknown;
307}
308
309/**
310 * Scales its content down (never up) so that a long text still fits the canvas, on every size and
311 * aspect ratio; the camera and the content can move freely inside.
312 */
313function FitToView({ children, size, maxWidth = 0.86, maxHeight = 0.62, measureKey }: FitToViewProps) {
314 const outer = useRef<THREE.Group>(null);
315 const inner = useRef<THREE.Group>(null);
316 const measured = useRef(new THREE.Vector2(1, 1));
317 const viewport = useThree((state) => state.viewport);
318
319 useLayoutEffect(() => {
320 if (size) {
321 measured.current.set(size[0], size[1]);
322 return;
323 }
324 if (!inner.current || !outer.current) return;
325 // World-space box, divided by the current fit scale: the size of the content at scale 1
326 outer.current.updateWorldMatrix(true, true);
327 const box = new THREE.Box3().setFromObject(inner.current, true);
328 const scale = outer.current.getWorldScale(new THREE.Vector3()).x || 1;
329 if (!box.isEmpty()) measured.current.set((box.max.x - box.min.x) / scale, (box.max.y - box.min.y) / scale);
330 }, [size, measureKey]);
331
332 useFrame(() => {
333 if (!outer.current) return;
334 const { x, y } = measured.current;
335 const scale = Math.min(1, (viewport.width * maxWidth) / Math.max(x, 1e-3), (viewport.height * maxHeight) / Math.max(y, 1e-3));
336 outer.current.scale.setScalar(scale);
337 });
338
339 return (
340 <group ref={outer}>
341 <group ref={inner}>{children}</group>
342 </group>
343 );
344}
345
346/** The font of the page body, for text drawn on a 2D canvas. */
347function pageFontFamily() {
348 if (typeof document === "undefined") return "sans-serif";
349 return getComputedStyle(document.body).fontFamily || "sans-serif";
350}
351
352export interface MoebiusRibbonTextProps extends Pick<MaterialProps, "primaryColor">, Pick<Text3DProps, "text">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {
353 text: string;
354 /** Scrolling speed of the text along the ribbon (negative reverses it). Default 1. */
355 speed?: number;
356 primaryColor?: string;
357 /** @deprecated Use `primaryColor`. */
358 ribbonColor?: string;
359 textColor?: string;
360 /**
361 * Twist of the ribbon over one turn, in radians, rounded to a multiple of π: π is a Möbius strip
362 * (one side only: the text runs over both faces), 2π a full twist, 0 a flat ring. Default π.
363 */
364 twistAngle?: number;
365 /** CSS font the text is drawn with. Default: the page's font. */
366 fontFamily?: string;
367}
368
369const RADIUS = 1.6;
370const HALF_WIDTH = 0.42;
371const THICKNESS = 0.012;
372const SEGMENTS = 720; // along the ribbon (two laps)
373
374/**
375 * The ribbon, built as ONE strip running twice around the ring, slightly off its mid-surface: for an
376 * odd number of half twists the second lap is naturally the other face (the Möbius trick), for an
377 * even number it is pushed to the other face. Each face therefore gets text reading the right way.
378 */
379function createRibbon(halfTwists: number, tiles: number) {
380 const positions: number[] = [];
381 const normals: number[] = [];
382 const uvs: number[] = [];
383 const indices: number[] = [];
384 const center = new THREE.Vector3();
385 const radial = new THREE.Vector3();
386 const across = new THREE.Vector3();
387 const normal = new THREE.Vector3();
388 const up = new THREE.Vector3(0, 0, 1);
389
390 for (let i = 0; i <= SEGMENTS; i++) {
391 const u = (i / SEGMENTS) * Math.PI * 4;
392 const theta = (halfTwists * u) / 2;
393 const side = halfTwists % 2 === 0 && u >= Math.PI * 2 ? -1 : 1;
394 center.set(Math.cos(u) * RADIUS, Math.sin(u) * RADIUS, 0);
395 radial.set(Math.cos(u), Math.sin(u), 0);
396 across.copy(radial).multiplyScalar(Math.cos(theta)).addScaledVector(up, Math.sin(theta));
397 normal.copy(radial).multiplyScalar(-Math.sin(theta)).addScaledVector(up, Math.cos(theta)).multiplyScalar(side);
398 for (const v of [-1, 1]) {
399 const p = center.clone().addScaledVector(across, v * HALF_WIDTH).addScaledVector(normal, THICKNESS / 2);
400 positions.push(p.x, p.y, p.z);
401 normals.push(normal.x, normal.y, normal.z);
402 // Mirror the text where the face looks the other way, so it always reads left to right
403 uvs.push((i / SEGMENTS) * tiles, side > 0 ? (1 - v) / 2 : (1 + v) / 2);
404 }
405 }
406 for (let i = 0; i < SEGMENTS; i++) {
407 const a = i * 2;
408 indices.push(a, a + 2, a + 1, a + 1, a + 2, a + 3);
409 }
410 const geometry = new THREE.BufferGeometry();
411 geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
412 geometry.setAttribute("normal", new THREE.Float32BufferAttribute(normals, 3));
413 geometry.setAttribute("uv", new THREE.Float32BufferAttribute(uvs, 2));
414 geometry.setIndex(indices);
415 return geometry;
416}
417
418/** One tile of text (text + separator) on the ribbon color; returns its width/height ratio. */
419function createTextTile(text: string, ribbonColor: string, textColor: string, fontFamily?: string) {
420 const height = 128;
421 const canvas = document.createElement("canvas");
422 const ctx = canvas.getContext("2d")!;
423 const font = `800 ${Math.round(height * 0.56)}px ${fontFamily ?? pageFontFamily()}`;
424 const label = `${(text || " ").replace(/\s*\n\s*/g, " ").toUpperCase()} ✦ `;
425 ctx.font = font;
426 canvas.width = Math.ceil(ctx.measureText(label).width);
427 canvas.height = height;
428 ctx.fillStyle = ribbonColor;
429 ctx.fillRect(0, 0, canvas.width, height);
430 ctx.font = font;
431 ctx.fillStyle = textColor;
432 ctx.textBaseline = "middle";
433 ctx.fillText(label, 0, height * 0.54);
434 // Thin rails along both edges of the ribbon
435 ctx.fillRect(0, 6, canvas.width, 3);
436 ctx.fillRect(0, height - 9, canvas.width, 3);
437 const texture = new THREE.CanvasTexture(canvas);
438 texture.colorSpace = THREE.SRGBColorSpace;
439 texture.wrapS = THREE.RepeatWrapping;
440 texture.anisotropy = 8;
441 return { texture, aspect: canvas.width / height };
442}
443
444const Ribbon = memo(function Ribbon({ text, speed, ribbonColor, textColor, twistAngle, fontFamily }: Required<Omit<MoebiusRibbonTextProps, "primaryColor" | "pauseWhenOffscreen" | "lowPowerMode" | "fontFamily">> & { fontFamily?: string }) {
445 const reducedMotion = usePrefersReducedMotion();
446 const pointer = useCanvasPointer();
447 const group = useRef<THREE.Group>(null);
448 const halfTwists = Math.round(twistAngle / Math.PI);
449
450 const tile = useMemo(() => createTextTile(text, ribbonColor, textColor, fontFamily), [text, ribbonColor, textColor, fontFamily]);
451 useEffect(() => () => tile.texture.dispose(), [tile]);
452
453 // As many whole tiles as fit along the two laps, so the text loops without a seam
454 const tiles = useMemo(() => {
455 const length = Math.PI * 4 * RADIUS;
456 return Math.max(1, Math.round(length / (tile.aspect * HALF_WIDTH * 2)));
457 }, [tile.aspect]);
458 const geometry = useMemo(() => createRibbon(halfTwists, tiles), [halfTwists, tiles]);
459 useEffect(() => () => geometry.dispose(), [geometry]);
460
461 const material = useMemo(() => new THREE.MeshStandardMaterial({ side: THREE.DoubleSide, roughness: 0.42, metalness: 0.15 }), []);
462 useEffect(() => () => material.dispose(), [material]);
463 useEffect(() => {
464 material.map = tile.texture;
465 material.emissiveMap = tile.texture;
466 material.emissive.set("#ffffff");
467 material.emissiveIntensity = 0.32;
468 material.needsUpdate = true;
469 }, [material, tile]);
470
471 const spin = useRef(0);
472 useFrame((_, delta) => {
473 const dt = Math.min(delta, 1 / 30);
474 const motion = reducedMotion ? 0.15 : 1;
475 tile.texture.offset.x -= dt * speed * 0.18 * motion;
476 spin.current += dt * 0.22 * motion;
477 const g = group.current;
478 if (!g) return;
479 const p = pointer.current;
480 // Slow drift in space, tilted toward the pointer
481 g.rotation.x = THREE.MathUtils.damp(g.rotation.x, -0.9 + (p.inside ? -p.ndc.y * 0.45 : 0), 2.5, dt);
482 g.rotation.y = THREE.MathUtils.damp(g.rotation.y, 0.25 + (p.inside ? p.ndc.x * 0.5 : 0), 2.5, dt);
483 g.rotation.z = spin.current;
484 });
485
486 const extent = (RADIUS + HALF_WIDTH) * 2;
487 return (
488 <FitToView size={[extent, extent * 0.8]} maxWidth={0.86} maxHeight={0.7}>
489 <group ref={group}>
490 <mesh geometry={geometry} material={material} />
491 </group>
492 </FitToView>
493 );
494});
495
496/**
497 * Your text running forever along a ribbon slowly turning in space — a Möbius strip by default, so
498 * the text glides from one face onto the other without ever reaching an end.
499 */
500function MoebiusRibbonText3D({
501 text,
502 speed = 1,
503 primaryColor,
504 ribbonColor = primaryColor ?? "#111114",
505 textColor = "#f4f4f5",
506 twistAngle = Math.PI,
507 fontFamily,
508 pauseWhenOffscreen,
509 lowPowerMode,
510}: MoebiusRibbonTextProps) {
511 return (
512 <TypeCanvas pauseWhenOffscreen={pauseWhenOffscreen} lowPowerMode={lowPowerMode} label={text} camera={{ position: [0, 0, 6], fov: 40 }}>
513 <ambientLight intensity={0.9} />
514 <directionalLight position={[2, 3, 5]} intensity={1.8} />
515 <directionalLight position={[-4, -2, -3]} intensity={0.6} />
516 <Ribbon text={text} speed={speed} ribbonColor={ribbonColor} textColor={textColor} twistAngle={twistAngle} fontFamily={fontFamily} />
517 </TypeCanvas>
518 );
519}
520
521export default memo(MoebiusRibbonText3D);
03

Drop it in a page

Updated live with the settings above.

app/page.tsx
1import MoebiusRibbonText3D from "@/components/MoebiusRibbonText3D";
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 <MoebiusRibbonText3D
8 text="INFINITE LOOP"
9 speed={1}
10 twistAngle={3.14159}
11 primaryColor="#111114"
12 textColor="#f4f4f5"
13 />
14 </div>
15 );
16}
Next componentGlass Holo Text→