← All components Next componentVisionOS Pill→
Typography · Stone
Monolith Shadow
Letters carved in relief on a stone slab, a grazing light led by the pointer throwing long dramatic shadows.
<MonolithShadowText3D />Live
The light follows your cursor
Customize
Stone#5b5751
Light#ffd9a8
Installation
Use it in your project
Or skip the copy-paste
One command: writes the file and installs the dependencies.
$ npx deepui-cli add monolith-shadow
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/MonolithShadowText3D.tsx and paste it in.
components/MonolithShadowText3D.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";2021/**22 * The shared props API of DeepUI's individual 3D components (not the full-page templates, which keep23 * their own tailored scenes).24 *25 * The props are grouped by concern. A component extends ONLY the groups it really applies, so its26 * type never advertises a knob that does nothing (a card has no particles, a background has no tilt):27 *28 * interface MyCardProps extends CursorProps, TiltProps, MaterialProps, PerformanceProps { … }29 *30 * `Base3DComponentProps` is every group at once, for tooling that handles any component. Same name,31 * same unit and same meaning everywhere; the default values live in DEFAULT_3D_PROPS. These files are32 * inlined into each component's single-file bundle (lib/bundle-source.mjs), only what it uses.33 */3435/** Which rotation axes follow the pointer. "x-only": the object nods (up / down); "y-only": it turns (left / right). */36export type TiltAxis = "both" | "x-only" | "y-only" | "none";3738/** 1. Cursor: how the pointer pulls, pushes and drags the object. */39interface CursorProps {40 /** 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). */41 cursorRadius?: number;42 /** Positive pulls things towards the pointer, negative pushes them away (repulsion, shockwave). Default 1. */43 cursorForce?: number;44 /** How far the object slides towards the pointer, 0 (stays put) to 1 (follows closely). Default 0. */45 magneticStrength?: number;46 /** Share of the remaining distance the motion closes each frame (at 60 fps), 0.01 (heavy, slow) to 1 (instant). Default 0.1. */47 cursorDamping?: number;48}4950/** 2. Tilt and parallax: the object leans towards the pointer, its layers slide against each other. */51interface TiltProps {52 /** Largest lean towards the pointer, in degrees. Default 15. */53 maxTiltAngle?: number;54 /** Axes that follow the pointer. Default "both". */55 tiltAxis?: TiltAxis;56 /** Lean away from the pointer instead of towards it. Default false. */57 invertTilt?: boolean;58 /** How far apart the depth layers slide when the object tilts, 0 (flat) to 2. Default 1. */59 parallaxOffset?: number;60}6162/** 3. Text and 3D typography, for components that draw a label. */63interface Text3DProps {64 /** The label drawn by the component. */65 text?: string;66 /** Scale of the lettering. Default 1. */67 fontSize?: number;68 /** Extrusion depth of 3D letters. Default 0.2. */69 textDepth?: number;70 /** Bevelled, light-catching edges on 3D letters. Default true. */71 bevelEnabled?: boolean;72 /** Custom font: a .woff / .ttf (flat text) or a typeface .json (extruded text). */73 fontUrl?: string;74}7576/** 4. Rendering, materials and glow. */77interface MaterialProps {78 /** Main color of the object. Default "#6366f1". */79 primaryColor?: string;80 /** Color of the glow. Default "#00f0ff". */81 emissiveColor?: string;82 /** Strength of the glow, 0 (none) to 3. Default 1. */83 emissiveIntensity?: number;84 /** 0 (mirror, glass) to 1 (matte). Default 0.3. */85 roughness?: number;86 /** 0 (plastic, organic) to 1 (metal). Default 0.5. */87 metalness?: number;88 /** 0 (opaque) to 1 (clear glass): see-through, refracting surfaces. Default 0. */89 transmission?: number;90 /** Technical wireframe rendering. Default false. */91 wireframe?: boolean;92}9394/** 5. Particles, idle motion and shader animation. */95interface MotionProps {96 /** Number of instanced elements. Default depends on the component. */97 particleCount?: number;98 /** Spin on its own, in radians per second (negative: the other way; 0.5 ≈ one turn in 12 s). Default 0. */99 autoRotateSpeed?: number;100 /** Pulses or ripples per second. Default 1. */101 pulseRate?: number;102 /** Amplitude of the noise deformation, 0 (none) to 2. Default 1. */103 displacementScale?: number;104}105106/** 6. Environment and camera. */107interface EnvironmentProps {108 /** Camera field of view, in degrees. Default depends on the component. */109 cameraFov?: number;110 /** Color of the depth fog. Default "#0a0a0a". */111 fogColor?: string;112 /** Thickness of the fog, 0 (none) to 0.2. Default 0. */113 fogDensity?: number;114}115116/** 7. Performance and accessibility. */117interface PerformanceProps {118 /** Lighter rendering for weak devices: pixel ratio 1, fewer instances, smaller environment maps. Default false. */119 lowPowerMode?: boolean;120 /** Under the OS "reduce motion" setting, stop idle spin, pulses and deformation (pointer feedback stays). Default true. */121 respectReducedMotion?: boolean;122 /** Stop the render loop while the component is scrolled out of view. Default true. */123 pauseWhenOffscreen?: boolean;124}125126/** Every group at once. Components extend only the groups they apply (see the top of this file). */127interface Base3DComponentProps128 extends CursorProps,129 TiltProps,130 Text3DProps,131 MaterialProps,132 MotionProps,133 EnvironmentProps,134 PerformanceProps {}135136type Defaults = Required<Omit<Base3DComponentProps, "text" | "fontUrl" | "particleCount" | "cameraFov">>;137138/** The values a prop takes when it is left out. A component may override one, and then documents it. */139const DEFAULT_3D_PROPS: Defaults = {140 cursorRadius: 220,141 cursorForce: 1,142 magneticStrength: 0,143 cursorDamping: 0.1,144 maxTiltAngle: 15,145 tiltAxis: "both",146 invertTilt: false,147 parallaxOffset: 1,148 fontSize: 1,149 textDepth: 0.2,150 bevelEnabled: true,151 primaryColor: "#6366f1",152 emissiveColor: "#00f0ff",153 emissiveIntensity: 1,154 roughness: 0.3,155 metalness: 0.5,156 transmission: 0,157 wireframe: false,158 autoRotateSpeed: 0,159 pulseRate: 1,160 displacementScale: 1,161 fogColor: "#0a0a0a",162 fogDensity: 0,163 lowPowerMode: false,164 respectReducedMotion: true,165 pauseWhenOffscreen: true,166};167168/**169 * Typeface font used when none is given: Helvetiker Bold from the three.js examples (Latin letters,170 * digits and punctuation). Any font can be converted to this JSON format with facetype.js.171 */172const DEFAULT_FONT = "https://cdn.jsdelivr.net/npm/three@0.170.0/examples/fonts/helvetiker_bold.typeface.json";173174/** Fills the positioned parent and receives pointer events. */175const FILL_STYLE: CSSProperties = { position: "absolute", top: 0, left: 0, width: "100%", height: "100%" };176177/** Visually hidden but read by screen readers (the canvas itself is aria-hidden). */178const SR_ONLY: CSSProperties = {179 position: "absolute",180 width: 1,181 height: 1,182 padding: 0,183 margin: -1,184 overflow: "hidden",185 clip: "rect(0, 0, 0, 0)",186 whiteSpace: "nowrap",187 border: 0,188};189190interface TypeCanvasProps extends Omit<CanvasProps, "children" | "style" | "frameloop" | "gl">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {191 children: ReactNode;192 /** The text, for screen readers. */193 label: string;194 /** HTML laid over the canvas (controls…). */195 overlay?: ReactNode;196}197198/**199 * Ready-to-use <Canvas> shared by the typography components: fills its positioned parent, pauses200 * its render loop while scrolled out of view, exposes the text to screen readers, and R3F disposes201 * the renderer and its WebGL context on unmount. A font that fails to load leaves an empty canvas.202 */203function TypeCanvas({ children, label, overlay, dpr = [1, 2], pauseWhenOffscreen = DEFAULT_3D_PROPS.pauseWhenOffscreen, lowPowerMode = DEFAULT_3D_PROPS.lowPowerMode, ...canvasProps }: TypeCanvasProps) {204 const containerRef = useRef<HTMLDivElement>(null);205 const [inView, setInView] = useState(true);206207 useEffect(() => {208 const el = containerRef.current;209 if (!el) return undefined;210 const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting));211 observer.observe(el);212 return () => observer.disconnect();213 }, []);214215 return (216 <div ref={containerRef} style={FILL_STYLE}>217 <span style={SR_ONLY}>{label}</span>218 <Canvas219 aria-hidden="true"220 dpr={lowPowerMode ? 1 : dpr}221 frameloop={inView || !pauseWhenOffscreen ? "always" : "never"}222 gl={{ antialias: true, alpha: true, powerPreference: "high-performance" }}223 style={{ touchAction: "pan-y" }}224 {...canvasProps}225 >226 <SceneBoundary>227 <Suspense fallback={null}>{children}</Suspense>228 </SceneBoundary>229 </Canvas>230 {overlay}231 </div>232 );233}234235class SceneBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {236 state = { failed: false };237 static getDerivedStateFromError() {238 return { failed: true };239 }240 render() {241 return this.state.failed ? null : this.props.children;242 }243}244245function usePrefersReducedMotion() {246 const [reduced, setReduced] = useState(false);247 useEffect(() => {248 const query = window.matchMedia("(prefers-reduced-motion: reduce)");249 const sync = () => setReduced(query.matches);250 sync();251 query.addEventListener("change", sync);252 return () => query.removeEventListener("change", sync);253 }, []);254 return reduced;255}256257interface CanvasPointer {258 /** Pointer position in normalized device coordinates of the canvas (-1..1). */259 ndc: THREE.Vector2;260 /** True while the pointer is over the canvas. */261 inside: boolean;262 /** Pointer speed, in NDC units per second (smoothed). */263 speed: number;264}265266/**267 * Tracks the pointer relative to the canvas through window listeners, so HTML laid over the canvas268 * never blocks it. Returns a ref read inside useFrame: pointer moves never re-render React.269 */270function useCanvasPointer(): RefObject<CanvasPointer> {271 const gl = useThree((state) => state.gl);272 const pointer = useRef<CanvasPointer>({ ndc: new THREE.Vector2(), inside: false, speed: 0 });273274 useEffect(() => {275 const el = gl.domElement;276 let lastTime = performance.now();277 const move = (event: PointerEvent) => {278 const rect = el.getBoundingClientRect();279 const p = pointer.current;280 const x = ((event.clientX - rect.left) / rect.width) * 2 - 1;281 const y = -((event.clientY - rect.top) / rect.height) * 2 + 1;282 const now = performance.now();283 const dt = Math.max(1, now - lastTime) / 1000;284 lastTime = now;285 p.speed = p.speed * 0.7 + (Math.hypot(x - p.ndc.x, y - p.ndc.y) / dt) * 0.3;286 p.ndc.set(x, y);287 p.inside = Math.abs(x) <= 1 && Math.abs(y) <= 1;288 };289 const leave = () => {290 pointer.current.inside = false;291 };292 window.addEventListener("pointermove", move, { passive: true });293 document.documentElement.addEventListener("pointerleave", leave);294 window.addEventListener("blur", leave);295 return () => {296 window.removeEventListener("pointermove", move);297 document.documentElement.removeEventListener("pointerleave", leave);298 window.removeEventListener("blur", leave);299 };300 }, [gl]);301302 return pointer;303}304305/** Loads a typeface JSON font (suspends until it is there; cached per URL). */306function useTypeface(url: string): Font {307 return useLoader(FontLoader, url);308}309310/**311 * Extruded text geometry, centered on the origin, rebuilt when the text or a parameter changes and312 * disposed when it is replaced or unmounted. Line breaks ("\n") start new lines.313 */314function useTextGeometry(text: string, fontUrl: string, params: Omit<TextGeometryParameters, "font">, transform?: (geometry: THREE.BufferGeometry) => THREE.BufferGeometry) {315 const font = useTypeface(fontUrl);316 const key = JSON.stringify(params);317 const geometry = useMemo(() => {318 const base = new TextGeometry(text || " ", { font, ...params });319 base.center();320 if (!transform) return base;321 const out = transform(base);322 if (out !== base) base.dispose();323 return out;324 // eslint-disable-next-line react-hooks/exhaustive-deps325 }, [text, font, key, transform]);326 useEffect(() => () => geometry.dispose(), [geometry]);327 return geometry;328}329330interface FitToViewProps {331 children: ReactNode;332 /** Size of the content in world units, at scale 1. Measured from the children when omitted. */333 size?: [number, number];334 /** Largest share of the view width the content may take. Default 0.86. */335 maxWidth?: number;336 /** Largest share of the view height the content may take. Default 0.62. */337 maxHeight?: number;338 /** Changes when the content changes, to measure it again. */339 measureKey?: unknown;340}341342/**343 * Scales its content down (never up) so that a long text still fits the canvas, on every size and344 * aspect ratio; the camera and the content can move freely inside.345 */346function FitToView({ children, size, maxWidth = 0.86, maxHeight = 0.62, measureKey }: FitToViewProps) {347 const outer = useRef<THREE.Group>(null);348 const inner = useRef<THREE.Group>(null);349 const measured = useRef(new THREE.Vector2(1, 1));350 const viewport = useThree((state) => state.viewport);351352 useLayoutEffect(() => {353 if (size) {354 measured.current.set(size[0], size[1]);355 return;356 }357 if (!inner.current || !outer.current) return;358 // World-space box, divided by the current fit scale: the size of the content at scale 1359 outer.current.updateWorldMatrix(true, true);360 const box = new THREE.Box3().setFromObject(inner.current, true);361 const scale = outer.current.getWorldScale(new THREE.Vector3()).x || 1;362 if (!box.isEmpty()) measured.current.set((box.max.x - box.min.x) / scale, (box.max.y - box.min.y) / scale);363 }, [size, measureKey]);364365 useFrame(() => {366 if (!outer.current) return;367 const { x, y } = measured.current;368 const scale = Math.min(1, (viewport.width * maxWidth) / Math.max(x, 1e-3), (viewport.height * maxHeight) / Math.max(y, 1e-3));369 outer.current.scale.setScalar(scale);370 });371372 return (373 <group ref={outer}>374 <group ref={inner}>{children}</group>375 </group>376 );377}378379export interface MonolithShadowTextProps extends Pick<Text3DProps, "textDepth" | "fontUrl" | "text" | "fontSize">, Pick<MaterialProps, "primaryColor">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {380 text: string;381 /** How far the letters stand out of the stone, in letter heights. Default 0.16. */382 textDepth?: number;383 /** @deprecated Use `textDepth`. */384 depth?: number;385 /** Rounded edge of the letters, in letter heights (0 = sharp). Default 0.025. */386 bevelSize?: number;387 primaryColor?: string;388 /** @deprecated Use `primaryColor`. */389 monolithColor?: string;390 lightColor?: string;391 /** Height of the letters in world units (long texts are scaled down to fit). Default 1. */392 fontSize?: number;393 /** URL of a typeface JSON font. Default: Helvetiker Bold. */394 fontUrl?: string;395 /** @deprecated Use `fontUrl`. */396 font?: string;397}398399const SLAB_DEPTH = 0.7;400401/** Procedural stone: speckled grain for the color, the same noise as a bump map. */402function createStoneTexture() {403 const size = 512;404 const canvas = document.createElement("canvas");405 canvas.width = canvas.height = size;406 const ctx = canvas.getContext("2d")!;407 const image = ctx.createImageData(size, size);408 // A few octaves of smoothed value noise, plus fine grain409 const octaves = [8, 32, 96].map((cells) => {410 const grid = new Float32Array((cells + 1) * (cells + 1)).map(() => Math.random());411 return { cells, grid };412 });413 const smooth = (t: number) => t * t * (3 - 2 * t);414 for (let y = 0; y < size; y++) {415 for (let x = 0; x < size; x++) {416 let v = 0;417 let weight = 0.55;418 for (const { cells, grid } of octaves) {419 const gx = (x / size) * cells;420 const gy = (y / size) * cells;421 const ix = Math.floor(gx);422 const iy = Math.floor(gy);423 const fx = smooth(gx - ix);424 const fy = smooth(gy - iy);425 const at = (cx: number, cy: number) => grid[(cy % cells) * (cells + 1) + (cx % cells)];426 const top = at(ix, iy) * (1 - fx) + at(ix + 1, iy) * fx;427 const bottom = at(ix, iy + 1) * (1 - fx) + at(ix + 1, iy + 1) * fx;428 v += (top * (1 - fy) + bottom * fy) * weight;429 weight *= 0.5;430 }431 v += Math.random() * 0.12;432 const c = Math.round(THREE.MathUtils.clamp(v, 0, 1) * 255);433 const i = (y * size + x) * 4;434 image.data[i] = image.data[i + 1] = image.data[i + 2] = c;435 image.data[i + 3] = 255;436 }437 }438 ctx.putImageData(image, 0, 0);439 const texture = new THREE.CanvasTexture(canvas);440 texture.wrapS = texture.wrapT = THREE.RepeatWrapping;441 return texture;442}443444const Monolith = memo(function Monolith({ text, depth, bevelSize, monolithColor, lightColor, fontSize, font }: Required<Omit<MonolithShadowTextProps, "textDepth" | "primaryColor" | "fontUrl" | "pauseWhenOffscreen" | "lowPowerMode">>) {445 const reducedMotion = usePrefersReducedMotion();446 const pointer = useCanvasPointer();447 const lamp = useRef<THREE.PointLight>(null);448 const bulb = useRef<THREE.Mesh>(null);449 const group = useRef<THREE.Group>(null);450451 const bevel = bevelSize * fontSize;452 const geometry = useTextGeometry(text, font, {453 size: fontSize,454 depth: Math.max(depth * fontSize, 0.01),455 curveSegments: 10,456 bevelEnabled: bevel > 0.0005,457 bevelThickness: bevel,458 bevelSize: bevel,459 bevelSegments: 4,460 });461462 // The slab is sized after the text, with a margin all around463 const slab = useMemo(() => {464 geometry.computeBoundingBox();465 const box = geometry.boundingBox!;466 const width = box.max.x - box.min.x + fontSize * 1.6;467 const height = box.max.y - box.min.y + fontSize * 1.4;468 return { width, height, textZ: SLAB_DEPTH / 2 + (box.max.z - box.min.z) / 2 };469 }, [geometry, fontSize]);470 const slabGeometry = useMemo(() => new THREE.BoxGeometry(slab.width, slab.height, SLAB_DEPTH), [slab]);471 useEffect(() => () => slabGeometry.dispose(), [slabGeometry]);472473 const stone = useMemo(() => createStoneTexture(), []);474 useEffect(() => () => stone.dispose(), [stone]);475 const materials = useMemo(() => {476 const slabMaterial = new THREE.MeshStandardMaterial({ roughness: 0.92, metalness: 0.02, bumpMap: stone, bumpScale: 1.2, roughnessMap: stone });477 const letterMaterial = new THREE.MeshStandardMaterial({ roughness: 0.6, metalness: 0.05, bumpMap: stone, bumpScale: 0.6 });478 return { slabMaterial, letterMaterial };479 }, [stone]);480 useEffect(481 () => () => {482 materials.slabMaterial.dispose();483 materials.letterMaterial.dispose();484 },485 [materials]486 );487 useEffect(() => {488 const repeat = Math.max(slab.width, slab.height) / 3;489 stone.repeat.set(repeat, repeat);490 materials.slabMaterial.color.set(monolithColor);491 // The letters are cut from the same stone, a little more polished492 materials.letterMaterial.color.set(monolithColor).offsetHSL(0, 0, 0.06);493 }, [materials, monolithColor, stone, slab]);494495 const time = useRef(0);496 useFrame((_, delta) => {497 const dt = Math.min(delta, 1 / 30);498 time.current += dt * (reducedMotion ? 0.2 : 1);499 const p = pointer.current;500 // A grazing light just above the stone, led by the pointer (it wanders on its own otherwise):501 // the closer it is to the surface, the longer the shadows of the letters502 const tx = p.inside ? p.ndc.x : Math.sin(time.current * 0.45) * 0.85;503 const ty = p.inside ? p.ndc.y : Math.sin(time.current * 0.3 + 1) * 0.6;504 const x = tx * slab.width * 0.62;505 const y = ty * slab.height * 0.7;506 const z = SLAB_DEPTH / 2 + fontSize * 0.45;507 const light = lamp.current;508 if (light) {509 light.position.set(THREE.MathUtils.damp(light.position.x, x, 4, dt), THREE.MathUtils.damp(light.position.y, y, 4, dt), z);510 bulb.current?.position.copy(light.position);511 }512 if (group.current) {513 group.current.rotation.y = THREE.MathUtils.damp(group.current.rotation.y, -tx * 0.08, 2, dt);514 group.current.rotation.x = THREE.MathUtils.damp(group.current.rotation.x, ty * 0.05, 2, dt);515 }516 });517518 return (519 <FitToView size={[slab.width, slab.height]} maxWidth={0.9} maxHeight={0.82}>520 <group ref={group}>521 <mesh geometry={slabGeometry} material={materials.slabMaterial} receiveShadow />522 <mesh geometry={geometry} material={materials.letterMaterial} position={[0, 0, slab.textZ]} castShadow receiveShadow />523 </group>524 {/* Omnidirectional light skimming the stone: every letter throws its shadow away from it */}525 <pointLight526 ref={lamp}527 color={lightColor}528 intensity={14 * fontSize * fontSize}529 distance={0}530 decay={2}531 position={[0, 0, 1]}532 castShadow533 shadow-mapSize={[1024, 1024]}534 shadow-bias={-0.002}535 shadow-normalBias={0.02}536 shadow-radius={5}537 shadow-camera-near={0.02}538 shadow-camera-far={40}539 />540 {/* The light source itself, a small glowing bead */}541 <mesh ref={bulb}>542 <sphereGeometry args={[fontSize * 0.04, 16, 16]} />543 <meshBasicMaterial color={lightColor} toneMapped={false} />544 </mesh>545 </FitToView>546 );547});548549/**550 * Text carved in relief on a massive stone slab. A grazing light led by the pointer sweeps over the551 * stone and throws long, dramatic shadows from the letters.552 */553function MonolithShadowText3D({554 text,555 textDepth,556 depth = textDepth ?? 0.16,557 bevelSize = 0.025,558 primaryColor,559 monolithColor = primaryColor ?? "#5b5751",560 lightColor = "#ffd9a8",561 fontSize = 1,562 fontUrl,563 font = fontUrl ?? DEFAULT_FONT,564 pauseWhenOffscreen,565 lowPowerMode,566}: MonolithShadowTextProps) {567 return (568 <TypeCanvas pauseWhenOffscreen={pauseWhenOffscreen} lowPowerMode={lowPowerMode} label={text} shadows="soft" camera={{ position: [0, 0, 7], fov: 36 }}>569 <ambientLight intensity={0.08} />570 <hemisphereLight args={["#9ab", "#000", 0.35]} />571 <Monolith text={text} depth={depth} bevelSize={bevelSize} monolithColor={monolithColor} lightColor={lightColor} fontSize={fontSize} font={font} />572 </TypeCanvas>573 );574}575576export default memo(MonolithShadowText3D);
03
Drop it in a page
Updated live with the settings above.
app/page.tsx
1import MonolithShadowText3D from "@/components/MonolithShadowText3D";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 <MonolithShadowText3D8 text="MONOLITH"9 textDepth={0.16}10 bevelSize={0.025}11 fontSize={1}12 primaryColor="#5b5751"13 lightColor="#ffd9a8"14 />15 </div>16 );17}