← All components Next componentVoxel Audio Text→
Typography · Glass
Glass Holo Text
Thick frosted-glass letters refracting and splitting a rainbow beam, the reflections sliding as the camera follows the pointer.
<GlassmorphicHoloText3D />Live
Move to turn the lightGlass
Customize
Installation
Use it in your project
Or skip the copy-paste
One command: writes the file and installs the dependencies.
$ npx deepui-cli add glass-holo
01
Install
The 3D packages this component is built on.
$ npm install three @react-three/fiber @react-three/drei && npm install -D @types/three
02
Add the component
One self-contained file: create components/GlassmorphicHoloText3D.tsx and paste it in.
components/GlassmorphicHoloText3D.tsx
1"use client";23import {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 { Environment, Lightformer, MeshTransmissionMaterial } from "@react-three/drei";2122/**23 * The shared props API of DeepUI's individual 3D components (not the full-page templates, which keep24 * their own tailored scenes).25 *26 * The props are grouped by concern. A component extends ONLY the groups it really applies, so its27 * 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 are33 * inlined into each component's single-file bundle (lib/bundle-source.mjs), only what it uses.34 */3536/** 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";3839/** 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}5051/** 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}6263/** 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}7677/** 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}9495/** 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}106107/** 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}116117/** 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}126127/** Every group at once. Components extend only the groups they apply (see the top of this file). */128interface Base3DComponentProps129 extends CursorProps,130 TiltProps,131 Text3DProps,132 MaterialProps,133 MotionProps,134 EnvironmentProps,135 PerformanceProps {}136137type Defaults = Required<Omit<Base3DComponentProps, "text" | "fontUrl" | "particleCount" | "cameraFov">>;138139/** 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};168169/**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";174175/** Fills the positioned parent and receives pointer events. */176const FILL_STYLE: CSSProperties = { position: "absolute", top: 0, left: 0, width: "100%", height: "100%" };177178/** 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};190191interface 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}198199/**200 * Ready-to-use <Canvas> shared by the typography components: fills its positioned parent, pauses201 * its render loop while scrolled out of view, exposes the text to screen readers, and R3F disposes202 * 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);207208 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 }, []);215216 return (217 <div ref={containerRef} style={FILL_STYLE}>218 <span style={SR_ONLY}>{label}</span>219 <Canvas220 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}235236class 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}245246function 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}257258interface 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}266267/**268 * Tracks the pointer relative to the canvas through window listeners, so HTML laid over the canvas269 * 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 });274275 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]);302303 return pointer;304}305306/** Loads a typeface JSON font (suspends until it is there; cached per URL). */307function useTypeface(url: string): Font {308 return useLoader(FontLoader, url);309}310311/**312 * Extruded text geometry, centered on the origin, rebuilt when the text or a parameter changes and313 * disposed when it is replaced or unmounted. Line breaks ("\n") start new lines.314 */315function useTextGeometry(text: string, fontUrl: string, params: Omit<TextGeometryParameters, "font">, transform?: (geometry: THREE.BufferGeometry) => THREE.BufferGeometry) {316 const font = useTypeface(fontUrl);317 const key = JSON.stringify(params);318 const geometry = useMemo(() => {319 const base = new TextGeometry(text || " ", { font, ...params });320 base.center();321 if (!transform) return base;322 const out = transform(base);323 if (out !== base) base.dispose();324 return out;325 // eslint-disable-next-line react-hooks/exhaustive-deps326 }, [text, font, key, transform]);327 useEffect(() => () => geometry.dispose(), [geometry]);328 return geometry;329}330331interface FitToViewProps {332 children: ReactNode;333 /** Size of the content in world units, at scale 1. Measured from the children when omitted. */334 size?: [number, number];335 /** Largest share of the view width the content may take. Default 0.86. */336 maxWidth?: number;337 /** Largest share of the view height the content may take. Default 0.62. */338 maxHeight?: number;339 /** Changes when the content changes, to measure it again. */340 measureKey?: unknown;341}342343/**344 * Scales its content down (never up) so that a long text still fits the canvas, on every size and345 * aspect ratio; the camera and the content can move freely inside.346 */347function FitToView({ children, size, maxWidth = 0.86, maxHeight = 0.62, measureKey }: FitToViewProps) {348 const outer = useRef<THREE.Group>(null);349 const inner = useRef<THREE.Group>(null);350 const measured = useRef(new THREE.Vector2(1, 1));351 const viewport = useThree((state) => state.viewport);352353 useLayoutEffect(() => {354 if (size) {355 measured.current.set(size[0], size[1]);356 return;357 }358 if (!inner.current || !outer.current) return;359 // World-space box, divided by the current fit scale: the size of the content at scale 1360 outer.current.updateWorldMatrix(true, true);361 const box = new THREE.Box3().setFromObject(inner.current, true);362 const scale = outer.current.getWorldScale(new THREE.Vector3()).x || 1;363 if (!box.isEmpty()) measured.current.set((box.max.x - box.min.x) / scale, (box.max.y - box.min.y) / scale);364 }, [size, measureKey]);365366 useFrame(() => {367 if (!outer.current) return;368 const { x, y } = measured.current;369 const scale = Math.min(1, (viewport.width * maxWidth) / Math.max(x, 1e-3), (viewport.height * maxHeight) / Math.max(y, 1e-3));370 outer.current.scale.setScalar(scale);371 });372373 return (374 <group ref={outer}>375 <group ref={inner}>{children}</group>376 </group>377 );378}379380export interface GlassmorphicHoloTextProps extends Pick<Text3DProps, "fontUrl" | "text" | "fontSize">, Pick<MaterialProps, "transmission" | "roughness">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {381 text: string;382 /** How thick the glass looks to the light passing through it. Default 0.7. */383 thickness?: number;384 /** 0 = opaque, 1 = fully see-through glass. Default 1. */385 transmission?: number;386 /** Index of refraction (1 = air, 1.5 = glass, 2.4 = diamond). Default 1.5. */387 ior?: number;388 /** Rainbow split of the light; it grows while the pointer moves. Default 0.4. */389 chromaticAberration?: number;390 /** Height of the letters in world units (long texts are scaled down to fit). Default 1. */391 fontSize?: number;392 /** Frosting of the glass, 0 = clear. Default 0.18. */393 roughness?: number;394 /** URL of a typeface JSON font. Default: Helvetiker Bold. */395 fontUrl?: string;396 /** @deprecated Use `fontUrl`. */397 font?: string;398}399400// Behind the glass: dark field crossed by a slow rainbow beam (refracted and split by the letters)401const backdropVertex = /* glsl */ `402varying vec2 vUv;403void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }404`;405const backdropFragment = /* glsl */ `406uniform float uTime;407uniform float uAngle;408varying vec2 vUv;409vec3 spectrum(float t) { return 0.5 + 0.5 * cos(6.28318 * (t + vec3(0.0, 0.33, 0.67))); }410void main() {411 vec2 p = vUv - 0.5;412 vec2 dir = vec2(cos(uAngle), sin(uAngle));413 float across = dot(p, vec2(-dir.y, dir.x));414 float along = dot(p, dir);415 // The beam: a narrow diagonal band with a soft halo, its colors running along it416 float beam = exp(-pow(across * 30.0, 2.0)) + exp(-pow(across * 9.0, 2.0)) * 0.22;417 vec3 color = spectrum(along * 2.2 - uTime * 0.06 + across * 6.0) * beam;418 // Faint grid of light so the refraction has something to bend419 vec2 g = abs(fract(vUv * vec2(26.0, 15.0)) - 0.5);420 float grid = smoothstep(0.475, 0.5, max(g.x, g.y)) * 0.045;421 color += vec3(grid) + vec3(0.012, 0.01, 0.025);422 float vignette = smoothstep(0.62, 0.1, length(p * vec2(1.0, 1.4)));423 gl_FragColor = vec4(color * vignette, 1.0);424 #include <colorspace_fragment>425}426`;427428const Glass = memo(function Glass({429 text,430 thickness,431 transmission,432 ior,433 chromaticAberration,434 fontSize,435 roughness,436 font,437}: Required<Omit<GlassmorphicHoloTextProps, "fontUrl" | "pauseWhenOffscreen" | "lowPowerMode">>) {438 const reducedMotion = usePrefersReducedMotion();439 const pointer = useCanvasPointer();440 const mesh = useRef<THREE.Mesh>(null);441 const glass = useRef<THREE.MeshPhysicalMaterial & { chromaticAberration: number }>(null);442 const beam = useRef<THREE.Group>(null);443 const aberration = useRef(chromaticAberration);444445 const geometry = useTextGeometry(text, font, {446 size: fontSize,447 depth: fontSize * 0.42,448 curveSegments: 12,449 bevelEnabled: true,450 bevelThickness: fontSize * 0.1,451 bevelSize: fontSize * 0.05,452 bevelSegments: 6,453 });454455 const backdrop = useMemo(456 () =>457 new THREE.ShaderMaterial({458 uniforms: { uTime: { value: 0 }, uAngle: { value: 0.5 } },459 vertexShader: backdropVertex,460 fragmentShader: backdropFragment,461 depthWrite: false,462 }),463 []464 );465 useEffect(() => () => backdrop.dispose(), [backdrop]);466467 useFrame((state, delta) => {468 const dt = Math.min(delta, 1 / 30);469 const p = pointer.current;470 const x = p.inside ? p.ndc.x : Math.sin(state.clock.elapsedTime * 0.3) * 0.4;471 const y = p.inside ? p.ndc.y : Math.cos(state.clock.elapsedTime * 0.25) * 0.25;472473 // The camera follows the pointer around the word: the light crosses the letters differently474 const camera = state.camera;475 camera.position.x = THREE.MathUtils.damp(camera.position.x, x * 1.6, 2.5, dt);476 camera.position.y = THREE.MathUtils.damp(camera.position.y, y * 0.9, 2.5, dt);477 camera.lookAt(0, 0, 0);478479 backdrop.uniforms.uTime.value += dt * (reducedMotion ? 0.2 : 1);480 backdrop.uniforms.uAngle.value = THREE.MathUtils.damp(backdrop.uniforms.uAngle.value, 0.55 + x * 0.6, 2, dt);481 if (beam.current) beam.current.rotation.z = backdrop.uniforms.uAngle.value;482483 // Moving the pointer splits the light further, then it settles back484 const target = chromaticAberration + Math.min(p.inside ? p.speed : 0, 6) * 0.12;485 aberration.current = THREE.MathUtils.damp(aberration.current, target, 4, dt);486 if (glass.current) glass.current.chromaticAberration = aberration.current;487488 if (mesh.current) mesh.current.rotation.y = THREE.MathUtils.damp(mesh.current.rotation.y, x * 0.12, 3, dt);489 });490491 return (492 <>493 <mesh position={[0, 0, -3]} scale={[22, 13, 1]} material={backdrop}>494 <planeGeometry />495 </mesh>496 {/* Lights mirrored in the glass: a white key, and a rainbow bar that turns with the beam */}497 <Environment resolution={256}>498 <Lightformer form="rect" intensity={3} position={[0, 3, 4]} scale={[10, 1.4, 1]} />499 <Lightformer form="rect" intensity={1.2} position={[-6, 0, 2]} scale={[1, 6, 1]} color="#8be9ff" />500 <group ref={beam}>501 <Lightformer form="rect" intensity={2.4} position={[0, -2.5, 3]} scale={[12, 0.4, 1]} color="#ff7ae0" />502 <Lightformer form="rect" intensity={2.4} position={[0, -3.1, 3]} scale={[12, 0.4, 1]} color="#ffe27a" />503 </group>504 </Environment>505 <FitToView measureKey={geometry} maxWidth={0.82} maxHeight={0.5}>506 <mesh ref={mesh} geometry={geometry}>507 <MeshTransmissionMaterial508 ref={glass as never}509 transmission={transmission}510 thickness={thickness}511 ior={ior}512 chromaticAberration={chromaticAberration}513 roughness={roughness}514 anisotropicBlur={0.25}515 distortion={0.2}516 distortionScale={0.4}517 temporalDistortion={reducedMotion ? 0 : 0.08}518 backside519 backsideThickness={thickness * 0.5}520 samples={6}521 resolution={512}522 backsideResolution={256}523 color="#ffffff"524 attenuationColor="#e8f3ff"525 attenuationDistance={2.5}526 />527 </mesh>528 </FitToView>529 </>530 );531});532533/**534 * Thick frosted-glass letters floating in front of a rainbow beam: the glass refracts and splits the535 * light behind it, and the reflections slide across the letters as the camera follows the pointer.536 */537function GlassmorphicHoloText3D({538 text,539 thickness = 0.7,540 transmission = 1,541 ior = 1.5,542 chromaticAberration = 0.4,543 fontSize = 1,544 roughness = 0.18,545 fontUrl,546 font = fontUrl ?? DEFAULT_FONT,547 pauseWhenOffscreen,548 lowPowerMode,549}: GlassmorphicHoloTextProps) {550 return (551 <TypeCanvas pauseWhenOffscreen={pauseWhenOffscreen} lowPowerMode={lowPowerMode} label={text} camera={{ position: [0, 0, 6], fov: 40 }}>552 <Glass553 text={text}554 thickness={thickness}555 transmission={transmission}556 ior={ior}557 chromaticAberration={chromaticAberration}558 fontSize={fontSize}559 roughness={roughness}560 font={font}561 />562 </TypeCanvas>563 );564}565566export default memo(GlassmorphicHoloText3D);
03
Drop it in a page
Updated live with the settings above.
app/page.tsx
1import GlassmorphicHoloText3D from "@/components/GlassmorphicHoloText3D";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 <GlassmorphicHoloText3D8 text="PRISM"9 thickness={0.7}10 transmission={1}11 ior={1.5}12 chromaticAberration={0.4}13 roughness={0.18}14 fontSize={1}15 />16 </div>17 );18}