Loading…
← All components

Typography · Neon

Liquid Neon

Your text bent out of a glowing glass tube: it swells like a liquid, and the neon crackles on with ripples running from under the cursor.

<LiquidNeonText3D />Live
Miami

Customize

Neon#ff3df2

Installation

Use it in your project

Or skip the copy-paste

One command: writes the file and installs the dependencies.

$ npx deepui-cli add liquid-neon
01

Install

The 3D packages this component is built on.

$ npm install three @react-three/fiber @react-three/postprocessing postprocessing && npm install -D @types/three
02

Add the component

One self-contained file: create components/LiquidNeonText3D.tsx and paste it in.

components/LiquidNeonText3D.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 { FontLoader, type Font } from "three/examples/jsm/loaders/FontLoader.js";
18import { TextGeometry, type TextGeometryParameters } from "three/examples/jsm/geometries/TextGeometry.js";
19import { Canvas, useFrame, useLoader, useThree, type CanvasProps } from "@react-three/fiber";
20import { Bloom, EffectComposer } from "@react-three/postprocessing";
21
22/**
23 * The shared props API of DeepUI's individual 3D components (not the full-page templates, which keep
24 * their own tailored scenes).
25 *
26 * The props are grouped by concern. A component extends ONLY the groups it really applies, so its
27 * type never advertises a knob that does nothing (a card has no particles, a background has no tilt):
28 *
29 * interface MyCardProps extends CursorProps, TiltProps, MaterialProps, PerformanceProps { … }
30 *
31 * `Base3DComponentProps` is every group at once, for tooling that handles any component. Same name,
32 * same unit and same meaning everywhere; the default values live in DEFAULT_3D_PROPS. These files are
33 * inlined into each component's single-file bundle (lib/bundle-source.mjs), only what it uses.
34 */
35
36/** Which rotation axes follow the pointer. "x-only": the object nods (up / down); "y-only": it turns (left / right). */
37export type TiltAxis = "both" | "x-only" | "y-only" | "none";
38
39/** 1. Cursor: how the pointer pulls, pushes and drags the object. */
40interface CursorProps {
41 /** 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). */
42 cursorRadius?: number;
43 /** Positive pulls things towards the pointer, negative pushes them away (repulsion, shockwave). Default 1. */
44 cursorForce?: number;
45 /** How far the object slides towards the pointer, 0 (stays put) to 1 (follows closely). Default 0. */
46 magneticStrength?: number;
47 /** Share of the remaining distance the motion closes each frame (at 60 fps), 0.01 (heavy, slow) to 1 (instant). Default 0.1. */
48 cursorDamping?: number;
49}
50
51/** 2. Tilt and parallax: the object leans towards the pointer, its layers slide against each other. */
52interface TiltProps {
53 /** Largest lean towards the pointer, in degrees. Default 15. */
54 maxTiltAngle?: number;
55 /** Axes that follow the pointer. Default "both". */
56 tiltAxis?: TiltAxis;
57 /** Lean away from the pointer instead of towards it. Default false. */
58 invertTilt?: boolean;
59 /** How far apart the depth layers slide when the object tilts, 0 (flat) to 2. Default 1. */
60 parallaxOffset?: number;
61}
62
63/** 3. Text and 3D typography, for components that draw a label. */
64interface Text3DProps {
65 /** The label drawn by the component. */
66 text?: string;
67 /** Scale of the lettering. Default 1. */
68 fontSize?: number;
69 /** Extrusion depth of 3D letters. Default 0.2. */
70 textDepth?: number;
71 /** Bevelled, light-catching edges on 3D letters. Default true. */
72 bevelEnabled?: boolean;
73 /** Custom font: a .woff / .ttf (flat text) or a typeface .json (extruded text). */
74 fontUrl?: string;
75}
76
77/** 4. Rendering, materials and glow. */
78interface MaterialProps {
79 /** Main color of the object. Default "#6366f1". */
80 primaryColor?: string;
81 /** Color of the glow. Default "#00f0ff". */
82 emissiveColor?: string;
83 /** Strength of the glow, 0 (none) to 3. Default 1. */
84 emissiveIntensity?: number;
85 /** 0 (mirror, glass) to 1 (matte). Default 0.3. */
86 roughness?: number;
87 /** 0 (plastic, organic) to 1 (metal). Default 0.5. */
88 metalness?: number;
89 /** 0 (opaque) to 1 (clear glass): see-through, refracting surfaces. Default 0. */
90 transmission?: number;
91 /** Technical wireframe rendering. Default false. */
92 wireframe?: boolean;
93}
94
95/** 5. Particles, idle motion and shader animation. */
96interface MotionProps {
97 /** Number of instanced elements. Default depends on the component. */
98 particleCount?: number;
99 /** Spin on its own, in radians per second (negative: the other way; 0.5 ≈ one turn in 12 s). Default 0. */
100 autoRotateSpeed?: number;
101 /** Pulses or ripples per second. Default 1. */
102 pulseRate?: number;
103 /** Amplitude of the noise deformation, 0 (none) to 2. Default 1. */
104 displacementScale?: number;
105}
106
107/** 6. Environment and camera. */
108interface EnvironmentProps {
109 /** Camera field of view, in degrees. Default depends on the component. */
110 cameraFov?: number;
111 /** Color of the depth fog. Default "#0a0a0a". */
112 fogColor?: string;
113 /** Thickness of the fog, 0 (none) to 0.2. Default 0. */
114 fogDensity?: number;
115}
116
117/** 7. Performance and accessibility. */
118interface PerformanceProps {
119 /** Lighter rendering for weak devices: pixel ratio 1, fewer instances, smaller environment maps. Default false. */
120 lowPowerMode?: boolean;
121 /** Under the OS "reduce motion" setting, stop idle spin, pulses and deformation (pointer feedback stays). Default true. */
122 respectReducedMotion?: boolean;
123 /** Stop the render loop while the component is scrolled out of view. Default true. */
124 pauseWhenOffscreen?: boolean;
125}
126
127/** Every group at once. Components extend only the groups they apply (see the top of this file). */
128interface Base3DComponentProps
129 extends CursorProps,
130 TiltProps,
131 Text3DProps,
132 MaterialProps,
133 MotionProps,
134 EnvironmentProps,
135 PerformanceProps {}
136
137type Defaults = Required<Omit<Base3DComponentProps, "text" | "fontUrl" | "particleCount" | "cameraFov">>;
138
139/** The values a prop takes when it is left out. A component may override one, and then documents it. */
140const DEFAULT_3D_PROPS: Defaults = {
141 cursorRadius: 220,
142 cursorForce: 1,
143 magneticStrength: 0,
144 cursorDamping: 0.1,
145 maxTiltAngle: 15,
146 tiltAxis: "both",
147 invertTilt: false,
148 parallaxOffset: 1,
149 fontSize: 1,
150 textDepth: 0.2,
151 bevelEnabled: true,
152 primaryColor: "#6366f1",
153 emissiveColor: "#00f0ff",
154 emissiveIntensity: 1,
155 roughness: 0.3,
156 metalness: 0.5,
157 transmission: 0,
158 wireframe: false,
159 autoRotateSpeed: 0,
160 pulseRate: 1,
161 displacementScale: 1,
162 fogColor: "#0a0a0a",
163 fogDensity: 0,
164 lowPowerMode: false,
165 respectReducedMotion: true,
166 pauseWhenOffscreen: true,
167};
168
169/**
170 * Typeface font used when none is given: Helvetiker Bold from the three.js examples (Latin letters,
171 * digits and punctuation). Any font can be converted to this JSON format with facetype.js.
172 */
173const DEFAULT_FONT = "https://cdn.jsdelivr.net/npm/three@0.170.0/examples/fonts/helvetiker_bold.typeface.json";
174
175/** Fills the positioned parent and receives pointer events. */
176const FILL_STYLE: CSSProperties = { position: "absolute", top: 0, left: 0, width: "100%", height: "100%" };
177
178/** Visually hidden but read by screen readers (the canvas itself is aria-hidden). */
179const SR_ONLY: CSSProperties = {
180 position: "absolute",
181 width: 1,
182 height: 1,
183 padding: 0,
184 margin: -1,
185 overflow: "hidden",
186 clip: "rect(0, 0, 0, 0)",
187 whiteSpace: "nowrap",
188 border: 0,
189};
190
191interface TypeCanvasProps extends Omit<CanvasProps, "children" | "style" | "frameloop" | "gl">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {
192 children: ReactNode;
193 /** The text, for screen readers. */
194 label: string;
195 /** HTML laid over the canvas (controls…). */
196 overlay?: ReactNode;
197}
198
199/**
200 * Ready-to-use <Canvas> shared by the typography components: fills its positioned parent, pauses
201 * its render loop while scrolled out of view, exposes the text to screen readers, and R3F disposes
202 * the renderer and its WebGL context on unmount. A font that fails to load leaves an empty canvas.
203 */
204function TypeCanvas({ children, label, overlay, dpr = [1, 2], pauseWhenOffscreen = DEFAULT_3D_PROPS.pauseWhenOffscreen, lowPowerMode = DEFAULT_3D_PROPS.lowPowerMode, ...canvasProps }: TypeCanvasProps) {
205 const containerRef = useRef<HTMLDivElement>(null);
206 const [inView, setInView] = useState(true);
207
208 useEffect(() => {
209 const el = containerRef.current;
210 if (!el) return undefined;
211 const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting));
212 observer.observe(el);
213 return () => observer.disconnect();
214 }, []);
215
216 return (
217 <div ref={containerRef} style={FILL_STYLE}>
218 <span style={SR_ONLY}>{label}</span>
219 <Canvas
220 aria-hidden="true"
221 dpr={lowPowerMode ? 1 : dpr}
222 frameloop={inView || !pauseWhenOffscreen ? "always" : "never"}
223 gl={{ antialias: true, alpha: true, powerPreference: "high-performance" }}
224 style={{ touchAction: "pan-y" }}
225 {...canvasProps}
226 >
227 <SceneBoundary>
228 <Suspense fallback={null}>{children}</Suspense>
229 </SceneBoundary>
230 </Canvas>
231 {overlay}
232 </div>
233 );
234}
235
236class SceneBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {
237 state = { failed: false };
238 static getDerivedStateFromError() {
239 return { failed: true };
240 }
241 render() {
242 return this.state.failed ? null : this.props.children;
243 }
244}
245
246function usePrefersReducedMotion() {
247 const [reduced, setReduced] = useState(false);
248 useEffect(() => {
249 const query = window.matchMedia("(prefers-reduced-motion: reduce)");
250 const sync = () => setReduced(query.matches);
251 sync();
252 query.addEventListener("change", sync);
253 return () => query.removeEventListener("change", sync);
254 }, []);
255 return reduced;
256}
257
258interface CanvasPointer {
259 /** Pointer position in normalized device coordinates of the canvas (-1..1). */
260 ndc: THREE.Vector2;
261 /** True while the pointer is over the canvas. */
262 inside: boolean;
263 /** Pointer speed, in NDC units per second (smoothed). */
264 speed: number;
265}
266
267/**
268 * Tracks the pointer relative to the canvas through window listeners, so HTML laid over the canvas
269 * never blocks it. Returns a ref read inside useFrame: pointer moves never re-render React.
270 */
271function useCanvasPointer(): RefObject<CanvasPointer> {
272 const gl = useThree((state) => state.gl);
273 const pointer = useRef<CanvasPointer>({ ndc: new THREE.Vector2(), inside: false, speed: 0 });
274
275 useEffect(() => {
276 const el = gl.domElement;
277 let lastTime = performance.now();
278 const move = (event: PointerEvent) => {
279 const rect = el.getBoundingClientRect();
280 const p = pointer.current;
281 const x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
282 const y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
283 const now = performance.now();
284 const dt = Math.max(1, now - lastTime) / 1000;
285 lastTime = now;
286 p.speed = p.speed * 0.7 + (Math.hypot(x - p.ndc.x, y - p.ndc.y) / dt) * 0.3;
287 p.ndc.set(x, y);
288 p.inside = Math.abs(x) <= 1 && Math.abs(y) <= 1;
289 };
290 const leave = () => {
291 pointer.current.inside = false;
292 };
293 window.addEventListener("pointermove", move, { passive: true });
294 document.documentElement.addEventListener("pointerleave", leave);
295 window.addEventListener("blur", leave);
296 return () => {
297 window.removeEventListener("pointermove", move);
298 document.documentElement.removeEventListener("pointerleave", leave);
299 window.removeEventListener("blur", leave);
300 };
301 }, [gl]);
302
303 return pointer;
304}
305
306const plane = new THREE.Plane();
307
308const raycaster = new THREE.Raycaster();
309
310/** Where the pointer ray meets the plane z = `z` (world space), written into `target`. */
311function pointerOnPlane(ndc: THREE.Vector2, camera: THREE.Camera, target: THREE.Vector3, z = 0) {
312 plane.set(new THREE.Vector3(0, 0, 1), -z);
313 raycaster.setFromCamera(ndc, camera);
314 return raycaster.ray.intersectPlane(plane, target) ?? target;
315}
316
317/** Loads a typeface JSON font (suspends until it is there; cached per URL). */
318function useTypeface(url: string): Font {
319 return useLoader(FontLoader, url);
320}
321
322/**
323 * Extruded text geometry, centered on the origin, rebuilt when the text or a parameter changes and
324 * disposed when it is replaced or unmounted. Line breaks ("\n") start new lines.
325 */
326function useTextGeometry(text: string, fontUrl: string, params: Omit<TextGeometryParameters, "font">, transform?: (geometry: THREE.BufferGeometry) => THREE.BufferGeometry) {
327 const font = useTypeface(fontUrl);
328 const key = JSON.stringify(params);
329 const geometry = useMemo(() => {
330 const base = new TextGeometry(text || " ", { font, ...params });
331 base.center();
332 if (!transform) return base;
333 const out = transform(base);
334 if (out !== base) base.dispose();
335 return out;
336 // eslint-disable-next-line react-hooks/exhaustive-deps
337 }, [text, font, key, transform]);
338 useEffect(() => () => geometry.dispose(), [geometry]);
339 return geometry;
340}
341
342interface FitToViewProps {
343 children: ReactNode;
344 /** Size of the content in world units, at scale 1. Measured from the children when omitted. */
345 size?: [number, number];
346 /** Largest share of the view width the content may take. Default 0.86. */
347 maxWidth?: number;
348 /** Largest share of the view height the content may take. Default 0.62. */
349 maxHeight?: number;
350 /** Changes when the content changes, to measure it again. */
351 measureKey?: unknown;
352}
353
354/**
355 * Scales its content down (never up) so that a long text still fits the canvas, on every size and
356 * aspect ratio; the camera and the content can move freely inside.
357 */
358function FitToView({ children, size, maxWidth = 0.86, maxHeight = 0.62, measureKey }: FitToViewProps) {
359 const outer = useRef<THREE.Group>(null);
360 const inner = useRef<THREE.Group>(null);
361 const measured = useRef(new THREE.Vector2(1, 1));
362 const viewport = useThree((state) => state.viewport);
363
364 useLayoutEffect(() => {
365 if (size) {
366 measured.current.set(size[0], size[1]);
367 return;
368 }
369 if (!inner.current || !outer.current) return;
370 // World-space box, divided by the current fit scale: the size of the content at scale 1
371 outer.current.updateWorldMatrix(true, true);
372 const box = new THREE.Box3().setFromObject(inner.current, true);
373 const scale = outer.current.getWorldScale(new THREE.Vector3()).x || 1;
374 if (!box.isEmpty()) measured.current.set((box.max.x - box.min.x) / scale, (box.max.y - box.min.y) / scale);
375 }, [size, measureKey]);
376
377 useFrame(() => {
378 if (!outer.current) return;
379 const { x, y } = measured.current;
380 const scale = Math.min(1, (viewport.width * maxWidth) / Math.max(x, 1e-3), (viewport.height * maxHeight) / Math.max(y, 1e-3));
381 outer.current.scale.setScalar(scale);
382 });
383
384 return (
385 <group ref={outer}>
386 <group ref={inner}>{children}</group>
387 </group>
388 );
389}
390
391export interface LiquidNeonTextProps extends Pick<MaterialProps, "emissiveColor" | "emissiveIntensity">, Pick<Text3DProps, "fontUrl" | "text" | "fontSize">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {
392 text: string;
393 /** Color of the tube light. Default "#ff3df2". */
394 emissiveColor?: string;
395 /** @deprecated Use `emissiveColor`. */
396 neonColor?: string;
397 /** Speed of the liquid waves (0 freezes them). Default 1. */
398 distortionSpeed?: number;
399 /** Strength of the glow around the letters. Default 1.2. */
400 emissiveIntensity?: number;
401 /** @deprecated Use `emissiveIntensity`. */
402 glowIntensity?: number;
403 /** Height of the letters in world units (long texts are scaled down to fit). Default 1. */
404 fontSize?: number;
405 /** URL of a typeface JSON font. Default: Helvetiker Bold. */
406 fontUrl?: string;
407 /** @deprecated Use `fontUrl`. */
408 font?: string;
409}
410
411// 3D simplex noise (Ashima Arts / Stefan Gustavson, MIT)
412const SIMPLEX = /* glsl */ `
413vec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
414vec4 mod289(vec4 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
415vec4 permute(vec4 x) { return mod289(((x * 34.0) + 1.0) * x); }
416vec4 taylorInvSqrt(vec4 r) { return 1.79284291400159 - 0.85373472095314 * r; }
417float snoise(vec3 v) {
418 const vec2 C = vec2(1.0 / 6.0, 1.0 / 3.0);
419 const vec4 D = vec4(0.0, 0.5, 1.0, 2.0);
420 vec3 i = floor(v + dot(v, C.yyy));
421 vec3 x0 = v - i + dot(i, C.xxx);
422 vec3 g = step(x0.yzx, x0.xyz);
423 vec3 l = 1.0 - g;
424 vec3 i1 = min(g.xyz, l.zxy);
425 vec3 i2 = max(g.xyz, l.zxy);
426 vec3 x1 = x0 - i1 + C.xxx;
427 vec3 x2 = x0 - i2 + C.yyy;
428 vec3 x3 = x0 - D.yyy;
429 i = mod289(i);
430 vec4 p = permute(permute(permute(i.z + vec4(0.0, i1.z, i2.z, 1.0)) + i.y + vec4(0.0, i1.y, i2.y, 1.0)) + i.x + vec4(0.0, i1.x, i2.x, 1.0));
431 float n_ = 0.142857142857;
432 vec3 ns = n_ * D.wyz - D.xzx;
433 vec4 j = p - 49.0 * floor(p * ns.z * ns.z);
434 vec4 x_ = floor(j * ns.z);
435 vec4 y_ = floor(j - 7.0 * x_);
436 vec4 x = x_ * ns.x + ns.yyyy;
437 vec4 y = y_ * ns.x + ns.yyyy;
438 vec4 h = 1.0 - abs(x) - abs(y);
439 vec4 b0 = vec4(x.xy, y.xy);
440 vec4 b1 = vec4(x.zw, y.zw);
441 vec4 s0 = floor(b0) * 2.0 + 1.0;
442 vec4 s1 = floor(b1) * 2.0 + 1.0;
443 vec4 sh = -step(h, vec4(0.0));
444 vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;
445 vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww;
446 vec3 p0 = vec3(a0.xy, h.x);
447 vec3 p1 = vec3(a0.zw, h.y);
448 vec3 p2 = vec3(a1.xy, h.z);
449 vec3 p3 = vec3(a1.zw, h.w);
450 vec4 norm = taylorInvSqrt(vec4(dot(p0, p0), dot(p1, p1), dot(p2, p2), dot(p3, p3)));
451 p0 *= norm.x; p1 *= norm.y; p2 *= norm.z; p3 *= norm.w;
452 vec4 m = max(0.6 - vec4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0);
453 m = m * m;
454 return 42.0 * dot(m * m, vec4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3)));
455}
456`;
457
458const vertexShader = /* glsl */ `
459uniform float uTime; // already scaled by distortionSpeed
460uniform vec3 uPointer; // pointer on the text plane, in geometry units
461uniform float uHover; // 0 → 1 while the pointer is near
462uniform float uSize; // font size: keeps the waves proportional to the letters
463
464varying vec3 vNormal;
465varying vec3 vView;
466varying float vWave;
467
468${SIMPLEX}
469
470void main() {
471 // The displacement depends on the position only (never on the face normal): vertices shared by the
472 // front and the sides of a letter move together, so the surface never tears
473 vec3 p = position;
474 vec2 q = p.xy / uSize;
475 vec2 toPointer = q - uPointer.xy / uSize;
476 float d = length(toPointer);
477 // Slow liquid swell everywhere, ripples running out from the pointer, a current through the letters
478 float swell = snoise(vec3(q * 0.9, uTime * 0.35));
479 float ripple = sin(d * 7.0 - uTime * 5.0) * exp(-d * 1.4) * uHover;
480 vec2 flow = vec2(snoise(vec3(q * 1.6, uTime * 0.5)), snoise(vec3(q * 1.6 + 17.0, uTime * 0.5)));
481 p.xy += (flow * 0.035 * uHover + toPointer / max(d, 0.001) * ripple * 0.035) * uSize;
482 p.z += (swell * 0.06 + ripple * 0.16) * uSize;
483 vWave = ripple;
484
485 vec4 mv = modelViewMatrix * vec4(p, 1.0);
486 vNormal = normalize(normalMatrix * normal);
487 vView = normalize(-mv.xyz);
488 gl_Position = projectionMatrix * mv;
489}
490`;
491
492const fragmentShader = /* glsl */ `
493uniform vec3 uColor;
494uniform float uGlow;
495uniform float uLight; // 0.3 idle → 1 lit (with its flicker)
496
497varying vec3 vNormal;
498varying vec3 vView;
499varying float vWave;
500
501void main() {
502 float facing = abs(dot(normalize(vNormal), normalize(vView)));
503 // A glass tube: saturated light, a hot pale core where it faces you, brighter rims
504 vec3 core = mix(uColor, vec3(1.0), 0.35);
505 vec3 color = mix(uColor * 1.1, core * 1.5, pow(facing, 6.0));
506 color += uColor * pow(1.0 - facing, 2.0) * 1.6;
507 color += mix(uColor, vec3(1.0), 0.5) * abs(vWave) * 1.4;
508 color *= uLight * (0.7 + uGlow * 0.8);
509 gl_FragColor = vec4(color, 1.0);
510}
511`;
512
513/**
514 * Splits every edge longer than `maxEdge` at its middle, pass after pass, so the letters can bend
515 * smoothly. The decision only depends on the edge itself, so the two triangles sharing it always
516 * split it the same way: no T-junction, no crack once the vertices move.
517 */
518function subdivideLongEdges(source: THREE.BufferGeometry, maxEdge: number, passes = 6) {
519 const flat = source.index ? source.toNonIndexed() : source;
520 let pos = Array.from(flat.attributes.position.array as Float32Array);
521 let nor = Array.from(flat.attributes.normal.array as Float32Array);
522 const limit = maxEdge * maxEdge;
523 for (let pass = 0; pass < passes; pass++) {
524 const nextPos: number[] = [];
525 const nextNor: number[] = [];
526 let split = false;
527 const vertex = (i: number) => ({ p: pos.slice(i * 3, i * 3 + 3), n: nor.slice(i * 3, i * 3 + 3) });
528 type V = ReturnType<typeof vertex>;
529 const mid = (a: V, b: V): V => {
530 const n = [a.n[0] + b.n[0], a.n[1] + b.n[1], a.n[2] + b.n[2]];
531 const len = Math.hypot(n[0], n[1], n[2]) || 1;
532 return { p: [(a.p[0] + b.p[0]) / 2, (a.p[1] + b.p[1]) / 2, (a.p[2] + b.p[2]) / 2], n: [n[0] / len, n[1] / len, n[2] / len] };
533 };
534 const long = (a: V, b: V) => (a.p[0] - b.p[0]) ** 2 + (a.p[1] - b.p[1]) ** 2 + (a.p[2] - b.p[2]) ** 2 > limit;
535 const emit = (...tri: V[]) => tri.forEach((v) => (nextPos.push(...v.p), nextNor.push(...v.n)));
536 for (let t = 0; t < pos.length / 9; t++) {
537 const a = vertex(t * 3);
538 const b = vertex(t * 3 + 1);
539 const c = vertex(t * 3 + 2);
540 const ab = long(a, b);
541 const bc = long(b, c);
542 const ca = long(c, a);
543 const count = Number(ab) + Number(bc) + Number(ca);
544 if (count) split = true;
545 if (count === 0) emit(a, b, c);
546 else if (count === 3) {
547 const m1 = mid(a, b), m2 = mid(b, c), m3 = mid(c, a);
548 emit(a, m1, m3, m1, b, m2, m3, m2, c, m1, m2, m3);
549 } else if (count === 1) {
550 // Rotate so the long edge is a→b
551 const [x, y, z] = ab ? [a, b, c] : bc ? [b, c, a] : [c, a, b];
552 const m = mid(x, y);
553 emit(x, m, z, m, y, z);
554 } else {
555 // Two long edges: rotate so they are x→y and y→z
556 const [x, y, z] = !ca ? [a, b, c] : !ab ? [b, c, a] : [c, a, b];
557 const m1 = mid(x, y), m2 = mid(y, z);
558 emit(m1, y, m2, x, m1, m2, x, m2, z);
559 }
560 }
561 pos = nextPos;
562 nor = nextNor;
563 if (!split) break;
564 }
565 if (flat !== source) flat.dispose();
566 const out = new THREE.BufferGeometry();
567 out.setAttribute("position", new THREE.Float32BufferAttribute(pos, 3));
568 out.setAttribute("normal", new THREE.Float32BufferAttribute(nor, 3));
569 out.computeBoundingBox();
570 return out;
571}
572
573const tessellate = (geometry: THREE.BufferGeometry) => {
574 geometry.computeBoundingBox();
575 const box = geometry.boundingBox!;
576 return subdivideLongEdges(geometry, Math.max(box.max.y - box.min.y, 0.1) * 0.07);
577};
578
579const NeonWord = memo(function NeonWord({ text, neonColor, distortionSpeed, glowIntensity, fontSize, font }: Required<Omit<LiquidNeonTextProps, "emissiveColor" | "emissiveIntensity" | "fontUrl" | "pauseWhenOffscreen" | "lowPowerMode">>) {
580 const reducedMotion = usePrefersReducedMotion();
581 const pointer = useCanvasPointer();
582 const mesh = useRef<THREE.Mesh>(null);
583 const hit = useRef(new THREE.Vector3());
584 const state = useRef({ time: 0, hover: 0, light: 0, flicker: 0 });
585
586 const geometry = useTextGeometry(
587 text,
588 font,
589 {
590 size: fontSize,
591 depth: fontSize * 0.2,
592 curveSegments: 10,
593 bevelEnabled: true,
594 bevelThickness: fontSize * 0.07,
595 bevelSize: fontSize * 0.05,
596 bevelSegments: 5,
597 },
598 tessellate
599 );
600
601 const material = useMemo(
602 () =>
603 new THREE.ShaderMaterial({
604 uniforms: {
605 uTime: { value: 0 },
606 uPointer: { value: new THREE.Vector3(999, 999, 0) },
607 uHover: { value: 0 },
608 uSize: { value: 1 },
609 uColor: { value: new THREE.Color() },
610 uGlow: { value: 1 },
611 uLight: { value: 0 },
612 },
613 vertexShader,
614 fragmentShader,
615 toneMapped: false,
616 }),
617 []
618 );
619 useEffect(() => () => material.dispose(), [material]);
620 useEffect(() => {
621 material.uniforms.uColor.value.set(neonColor);
622 material.uniforms.uGlow.value = glowIntensity;
623 material.uniforms.uSize.value = fontSize;
624 }, [material, neonColor, glowIntensity, fontSize]);
625
626 useFrame((frame, delta) => {
627 const dt = Math.min(delta, 1 / 30);
628 const s = state.current;
629 const u = material.uniforms;
630 s.time += dt * distortionSpeed * (reducedMotion ? 0.2 : 1);
631 u.uTime.value = s.time;
632
633 // Pointer in the text's own units: the ripples start right under it
634 const p = pointer.current;
635 let near = 0;
636 if (p.inside && mesh.current) {
637 pointerOnPlane(p.ndc, frame.camera, hit.current);
638 mesh.current.worldToLocal(hit.current);
639 u.uPointer.value.copy(hit.current);
640 const box = geometry.boundingBox;
641 if (box) {
642 const dx = Math.max(box.min.x - hit.current.x, 0, hit.current.x - box.max.x);
643 const dy = Math.max(box.min.y - hit.current.y, 0, hit.current.y - box.max.y);
644 near = 1 - THREE.MathUtils.smoothstep(Math.hypot(dx, dy), 0, fontSize * 1.2);
645 }
646 }
647 s.hover = THREE.MathUtils.damp(s.hover, near, near > s.hover ? 6 : 2, dt);
648 u.uHover.value = s.hover;
649
650 // The tube lights up when it is approached, crackling for a moment, then holds steady
651 const target = 0.35 + s.hover * 0.65;
652 const rising = target - s.light > 0.02;
653 s.flicker = rising && !reducedMotion ? (Math.random() < 0.18 ? 0.35 : 1) : 1;
654 s.light = THREE.MathUtils.damp(s.light, target, rising ? 3 : 1.5, dt);
655 u.uLight.value = Math.max(0.12, s.light * s.flicker);
656
657 // Barely floating, leaning toward the pointer
658 if (mesh.current) {
659 mesh.current.rotation.x = THREE.MathUtils.damp(mesh.current.rotation.x, -p.ndc.y * 0.12 * (p.inside ? 1 : 0), 3, dt);
660 mesh.current.rotation.y = THREE.MathUtils.damp(mesh.current.rotation.y, p.ndc.x * 0.18 * (p.inside ? 1 : 0), 3, dt);
661 }
662 });
663
664 return (
665 <FitToView measureKey={geometry}>
666 <mesh ref={mesh} geometry={geometry} material={material} />
667 </FitToView>
668 );
669});
670
671/**
672 * Text bent out of a glowing glass tube: it swells like a liquid, and when the pointer comes close
673 * the neon crackles on while ripples run through the letters from under the cursor.
674 */
675function LiquidNeonText3D({
676 text,
677 emissiveColor,
678 neonColor = emissiveColor ?? "#ff3df2",
679 distortionSpeed = 1,
680 emissiveIntensity,
681 glowIntensity = emissiveIntensity ?? 1.2,
682 fontSize = 1,
683 fontUrl,
684 font = fontUrl ?? DEFAULT_FONT,
685 pauseWhenOffscreen,
686 lowPowerMode,
687}: LiquidNeonTextProps) {
688 return (
689 <TypeCanvas pauseWhenOffscreen={pauseWhenOffscreen} lowPowerMode={lowPowerMode} label={text} camera={{ position: [0, 0, 6], fov: 40 }}>
690 <NeonWord text={text} neonColor={neonColor} distortionSpeed={distortionSpeed} glowIntensity={glowIntensity} fontSize={fontSize} font={font} />
691 <EffectComposer multisampling={0}>
692 <Bloom mipmapBlur intensity={glowIntensity} luminanceThreshold={0.25} luminanceSmoothing={0.4} radius={0.75} />
693 </EffectComposer>
694 </TypeCanvas>
695 );
696}
697
698export default memo(LiquidNeonText3D);
03

Drop it in a page

Updated live with the settings above.

app/page.tsx
1import LiquidNeonText3D from "@/components/LiquidNeonText3D";
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 <LiquidNeonText3D
8 text="NEON DREAMS"
9 distortionSpeed={1}
10 emissiveIntensity={1.2}
11 fontSize={1}
12 emissiveColor="#ff3df2"
13 />
14 </div>
15 );
16}
Next componentKinetic Gravity→