← All components Next componentEnergy Portal Button→
Buttons · Button
3D Key Button
A thick, lit key cap that tilts towards the cursor and sinks when pressed.
<InteractiveButton3D />Live
Hover and press it
Customize
Base#6d28d9
Hover#8b5cf6
Installation
Use it in your project
Or skip the copy-paste
One command: writes the file and installs the dependencies.
$ npx deepui-cli add key-button
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/InteractiveButton3D.tsx and paste it in.
components/InteractiveButton3D.tsx
1"use client";23import {4 memo,5 useEffect,6 useLayoutEffect,7 useMemo,8 useRef,9 useState,10 type CSSProperties,11 type ReactNode,12 type RefObject,13} from "react";14import * as THREE from "three";15import { Canvas, useFrame, useThree, type CanvasProps, type ThreeEvent } from "@react-three/fiber";16import { Environment, Lightformer } from "@react-three/drei";1718/**19 * The shared props API of DeepUI's individual 3D components (not the full-page templates, which keep20 * their own tailored scenes).21 *22 * The props are grouped by concern. A component extends ONLY the groups it really applies, so its23 * type never advertises a knob that does nothing (a card has no particles, a background has no tilt):24 *25 * interface MyCardProps extends CursorProps, TiltProps, MaterialProps, PerformanceProps { … }26 *27 * `Base3DComponentProps` is every group at once, for tooling that handles any component. Same name,28 * same unit and same meaning everywhere; the default values live in DEFAULT_3D_PROPS. These files are29 * inlined into each component's single-file bundle (lib/bundle-source.mjs), only what it uses.30 */3132/** Which rotation axes follow the pointer. "x-only": the object nods (up / down); "y-only": it turns (left / right). */33export type TiltAxis = "both" | "x-only" | "y-only" | "none";3435/** 1. Cursor: how the pointer pulls, pushes and drags the object. */36interface CursorProps {37 /** 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). */38 cursorRadius?: number;39 /** Positive pulls things towards the pointer, negative pushes them away (repulsion, shockwave). Default 1. */40 cursorForce?: number;41 /** How far the object slides towards the pointer, 0 (stays put) to 1 (follows closely). Default 0. */42 magneticStrength?: number;43 /** Share of the remaining distance the motion closes each frame (at 60 fps), 0.01 (heavy, slow) to 1 (instant). Default 0.1. */44 cursorDamping?: number;45}4647/** 2. Tilt and parallax: the object leans towards the pointer, its layers slide against each other. */48interface TiltProps {49 /** Largest lean towards the pointer, in degrees. Default 15. */50 maxTiltAngle?: number;51 /** Axes that follow the pointer. Default "both". */52 tiltAxis?: TiltAxis;53 /** Lean away from the pointer instead of towards it. Default false. */54 invertTilt?: boolean;55 /** How far apart the depth layers slide when the object tilts, 0 (flat) to 2. Default 1. */56 parallaxOffset?: number;57}5859/** 3. Text and 3D typography, for components that draw a label. */60interface Text3DProps {61 /** The label drawn by the component. */62 text?: string;63 /** Scale of the lettering. Default 1. */64 fontSize?: number;65 /** Extrusion depth of 3D letters. Default 0.2. */66 textDepth?: number;67 /** Bevelled, light-catching edges on 3D letters. Default true. */68 bevelEnabled?: boolean;69 /** Custom font: a .woff / .ttf (flat text) or a typeface .json (extruded text). */70 fontUrl?: string;71}7273/** 4. Rendering, materials and glow. */74interface MaterialProps {75 /** Main color of the object. Default "#6366f1". */76 primaryColor?: string;77 /** Color of the glow. Default "#00f0ff". */78 emissiveColor?: string;79 /** Strength of the glow, 0 (none) to 3. Default 1. */80 emissiveIntensity?: number;81 /** 0 (mirror, glass) to 1 (matte). Default 0.3. */82 roughness?: number;83 /** 0 (plastic, organic) to 1 (metal). Default 0.5. */84 metalness?: number;85 /** 0 (opaque) to 1 (clear glass): see-through, refracting surfaces. Default 0. */86 transmission?: number;87 /** Technical wireframe rendering. Default false. */88 wireframe?: boolean;89}9091/** 5. Particles, idle motion and shader animation. */92interface MotionProps {93 /** Number of instanced elements. Default depends on the component. */94 particleCount?: number;95 /** Spin on its own, in radians per second (negative: the other way; 0.5 ≈ one turn in 12 s). Default 0. */96 autoRotateSpeed?: number;97 /** Pulses or ripples per second. Default 1. */98 pulseRate?: number;99 /** Amplitude of the noise deformation, 0 (none) to 2. Default 1. */100 displacementScale?: number;101}102103/** 6. Environment and camera. */104interface EnvironmentProps {105 /** Camera field of view, in degrees. Default depends on the component. */106 cameraFov?: number;107 /** Color of the depth fog. Default "#0a0a0a". */108 fogColor?: string;109 /** Thickness of the fog, 0 (none) to 0.2. Default 0. */110 fogDensity?: number;111}112113/** 7. Performance and accessibility. */114interface PerformanceProps {115 /** Lighter rendering for weak devices: pixel ratio 1, fewer instances, smaller environment maps. Default false. */116 lowPowerMode?: boolean;117 /** Under the OS "reduce motion" setting, stop idle spin, pulses and deformation (pointer feedback stays). Default true. */118 respectReducedMotion?: boolean;119 /** Stop the render loop while the component is scrolled out of view. Default true. */120 pauseWhenOffscreen?: boolean;121}122123/** Every group at once. Components extend only the groups they apply (see the top of this file). */124interface Base3DComponentProps125 extends CursorProps,126 TiltProps,127 Text3DProps,128 MaterialProps,129 MotionProps,130 EnvironmentProps,131 PerformanceProps {}132133type Defaults = Required<Omit<Base3DComponentProps, "text" | "fontUrl" | "particleCount" | "cameraFov">>;134135/** The values a prop takes when it is left out. A component may override one, and then documents it. */136const DEFAULT_3D_PROPS: Defaults = {137 cursorRadius: 220,138 cursorForce: 1,139 magneticStrength: 0,140 cursorDamping: 0.1,141 maxTiltAngle: 15,142 tiltAxis: "both",143 invertTilt: false,144 parallaxOffset: 1,145 fontSize: 1,146 textDepth: 0.2,147 bevelEnabled: true,148 primaryColor: "#6366f1",149 emissiveColor: "#00f0ff",150 emissiveIntensity: 1,151 roughness: 0.3,152 metalness: 0.5,153 transmission: 0,154 wireframe: false,155 autoRotateSpeed: 0,156 pulseRate: 1,157 displacementScale: 1,158 fogColor: "#0a0a0a",159 fogDensity: 0,160 lowPowerMode: false,161 respectReducedMotion: true,162 pauseWhenOffscreen: true,163};164165/** Inline widget: fills its positioned parent and receives pointer events. */166const FILL_STYLE: CSSProperties = { position: "absolute", top: 0, left: 0, width: "100%", height: "100%" };167168/** Cursor overlay: covers the viewport, above everything, never intercepts the page's events. */169const OVERLAY_STYLE: CSSProperties = {170 position: "fixed",171 top: 0,172 left: 0,173 width: "100%",174 height: "100%",175 pointerEvents: "none",176 zIndex: 9999,177};178179/** Visually hidden but reachable by keyboard and screen readers. */180const SR_ONLY: CSSProperties = {181 position: "absolute",182 width: 1,183 height: 1,184 padding: 0,185 margin: -1,186 overflow: "hidden",187 clip: "rect(0, 0, 0, 0)",188 whiteSpace: "nowrap",189 border: 0,190};191192interface UICanvasProps extends Omit<CanvasProps, "children" | "style" | "gl">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {193 children: ReactNode;194 /** Full-viewport, click-through overlay (cursors) instead of an inline widget. */195 overlay?: boolean;196}197198/**199 * Ready-to-use <Canvas>: pauses its render loop while scrolled out of view (pauseWhenOffscreen), pixel200 * ratio 1 in lowPowerMode; R3F disposes the renderer and its WebGL context on unmount.201 */202function UICanvas({ children, overlay = false, dpr = [1, 2], pauseWhenOffscreen = DEFAULT_3D_PROPS.pauseWhenOffscreen, lowPowerMode = DEFAULT_3D_PROPS.lowPowerMode, ...canvasProps }: UICanvasProps) {203 const containerRef = useRef<HTMLDivElement>(null);204 // In view at first: the first frame is always drawn before the loop can be paused205 const [inView, setInView] = useState(true);206 useEffect(() => {207 const el = containerRef.current;208 if (!el || !pauseWhenOffscreen) return undefined;209 const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting));210 observer.observe(el);211 return () => observer.disconnect();212 }, [pauseWhenOffscreen]);213 return (214 <div ref={containerRef} style={overlay ? OVERLAY_STYLE : FILL_STYLE} aria-hidden="true">215 <Canvas216 dpr={lowPowerMode ? 1 : dpr}217 frameloop={inView || !pauseWhenOffscreen ? "always" : "never"}218 gl={{ antialias: true, alpha: true, powerPreference: "high-performance" }}219 style={overlay ? { pointerEvents: "none" } : undefined}220 {...canvasProps}221 >222 {children}223 </Canvas>224 </div>225 );226}227228/**229 * Perspective camera placed so that 1 world unit = 1 CSS pixel on the z = 0 plane: widgets are laid230 * out in pixels like the rest of the page, and still get real depth (presses, tilts, shadows).231 */232function PixelPerspective({ fov = 30 }: { fov?: number }) {233 const camera = useThree((state) => state.camera) as THREE.PerspectiveCamera;234 const size = useThree((state) => state.size);235 useLayoutEffect(() => {236 camera.fov = fov;237 camera.near = 1;238 camera.far = 20000;239 camera.position.set(0, 0, size.height / 2 / Math.tan(THREE.MathUtils.degToRad(fov / 2)));240 camera.lookAt(0, 0, 0);241 camera.updateProjectionMatrix();242 }, [camera, size, fov]);243 return null;244}245246function pageFontFamily() {247 if (typeof document === "undefined") return "sans-serif";248 return getComputedStyle(document.body).fontFamily || "sans-serif";249}250251let measureContext: CanvasRenderingContext2D | null = null;252253/** Width of a label in CSS pixels, in the page's font. */254function measureLabel(text: string, fontSize: number, fontWeight = 600) {255 if (typeof document === "undefined") return text.length * fontSize * 0.6;256 measureContext ??= document.createElement("canvas").getContext("2d");257 if (!measureContext) return text.length * fontSize * 0.6;258 measureContext.font = `${fontWeight} ${fontSize}px ${pageFontFamily()}`;259 return measureContext.measureText(text).width;260}261262interface LabelOptions {263 text: string;264 /** Second, smaller line under the text. */265 subtext?: string;266 /** Glyph drawn before the text (emoji, arrow, symbol…). */267 icon?: string;268 width: number;269 height: number;270 color: string;271 /** Face color; transparent when omitted. */272 background?: string;273 fontSize?: number;274 fontWeight?: number;275 /** Wrap the text over several lines within the width (minus padding). */276 wrap?: boolean;277 align?: "center" | "left";278 /** Horizontal padding, in CSS pixels (used by wrapping and left alignment). Default 0. */279 padding?: number;280 /** Line height, as a multiple of the font size. Default 1.35. */281 lineHeight?: number;282}283284function wrapLines(ctx: CanvasRenderingContext2D, text: string, maxWidth: number) {285 const lines: string[] = [];286 let line = "";287 for (const word of text.split(/\s+/)) {288 const candidate = line ? `${line} ${word}` : word;289 if (line && ctx.measureText(candidate).width > maxWidth) {290 lines.push(line);291 line = word;292 } else {293 line = candidate;294 }295 }296 if (line) lines.push(line);297 return lines;298}299300function drawLabel(canvas: HTMLCanvasElement, o: LabelOptions) {301 // Drawn at 2× (or the screen's ratio) so the text stays crisp once mapped on its plane302 const scale = Math.min(Math.max(window.devicePixelRatio || 1, 2), 3);303 canvas.width = Math.max(2, Math.ceil(o.width * scale));304 canvas.height = Math.max(2, Math.ceil(o.height * scale));305 const ctx = canvas.getContext("2d");306 if (!ctx) return;307 ctx.setTransform(scale, 0, 0, scale, 0, 0);308 ctx.clearRect(0, 0, o.width, o.height);309 if (o.background) {310 ctx.fillStyle = o.background;311 ctx.fillRect(0, 0, o.width, o.height);312 }313314 const family = pageFontFamily();315 const size = o.fontSize ?? 15;316 const weight = o.fontWeight ?? 600;317 ctx.fillStyle = o.color;318 ctx.textBaseline = "middle";319 ctx.textAlign = "center";320321 const padding = o.padding ?? 0;322 const left = o.align === "left";323 ctx.textAlign = left ? "left" : "center";324 const x = left ? padding : o.width / 2;325326 let text = o.text;327 if (o.icon) text = `${o.icon} ${text}`;328 ctx.font = `${weight} ${size}px ${family}`;329330 if (o.wrap) {331 const step = size * (o.lineHeight ?? 1.35);332 const lines = wrapLines(ctx, text, o.width - padding * 2);333 // Only as many lines as fit; the last one kept ends with an ellipsis334 const maxLines = Math.max(1, Math.floor(o.height / step));335 if (lines.length > maxLines) {336 lines.length = maxLines;337 let last = lines[maxLines - 1];338 while (last && ctx.measureText(`${last}…`).width > o.width - padding * 2) last = last.slice(0, -1);339 lines[maxLines - 1] = `${last.trimEnd()}…`;340 }341 const top = o.height / 2 - ((lines.length - 1) * step) / 2;342 lines.forEach((line, i) => ctx.fillText(line, x, top + i * step));343 return;344 }345346 const mainY = o.subtext ? o.height * 0.4 : o.height / 2;347 ctx.fillText(text, x, mainY);348349 if (o.subtext) {350 ctx.globalAlpha = 0.7;351 ctx.font = `500 ${Math.round(size * 0.72)}px ${family}`;352 ctx.fillText(o.subtext, x, o.height * 0.7);353 ctx.globalAlpha = 1;354 }355}356357/**358 * Text drawn into a CanvasTexture, in the page's own font: no font file to download (unlike drei's359 * <Text>). Redrawn once web fonts finish loading; disposed on unmount.360 */361function useLabelTexture(options: LabelOptions) {362 const key = JSON.stringify(options);363 const [fontsVersion, setFontsVersion] = useState(0);364 useEffect(() => {365 let alive = true;366 document.fonts?.ready.then(() => {367 if (alive) setFontsVersion((v) => v + 1);368 });369 return () => {370 alive = false;371 };372 }, []);373374 const texture = useMemo(() => {375 const t = new THREE.CanvasTexture(document.createElement("canvas"));376 t.colorSpace = THREE.SRGBColorSpace;377 t.anisotropy = 4;378 return t;379 }, []);380381 useLayoutEffect(() => {382 drawLabel(texture.image as HTMLCanvasElement, JSON.parse(key) as LabelOptions);383 texture.needsUpdate = true;384 }, [texture, key, fontsVersion]);385386 useEffect(() => () => texture.dispose(), [texture]);387 return texture;388}389390/** Rounded-rectangle outline centered on the origin (radius clamped to a pill). */391function roundedRectShape(width: number, height: number, radius: number) {392 const r = Math.min(radius, width / 2, height / 2);393 const x = -width / 2;394 const y = -height / 2;395 const shape = new THREE.Shape();396 shape.moveTo(x + r, y);397 shape.lineTo(x + width - r, y);398 shape.quadraticCurveTo(x + width, y, x + width, y + r);399 shape.lineTo(x + width, y + height - r);400 shape.quadraticCurveTo(x + width, y + height, x + width - r, y + height);401 shape.lineTo(x + r, y + height);402 shape.quadraticCurveTo(x, y + height, x, y + height - r);403 shape.lineTo(x, y + r);404 shape.quadraticCurveTo(x, y, x + r, y);405 return shape;406}407408/** Bevelled, extruded rounded rectangle, centered on the origin (front face at +depth/2 + bevel). */409function createBevelledSlab(width: number, height: number, radius: number, depth: number, bevel: number) {410 const geometry = new THREE.ExtrudeGeometry(roundedRectShape(width - bevel * 2, height - bevel * 2, Math.max(0, radius - bevel)), {411 depth,412 bevelEnabled: true,413 bevelThickness: bevel,414 bevelSize: bevel,415 bevelSegments: 6,416 curveSegments: 24,417 });418 geometry.translate(0, 0, -depth / 2);419 return geometry;420}421422interface Spring {423 value: number;424 velocity: number;425}426427/** Damped spring step: overshoots a little, then settles. */428function stepSpring(spring: Spring, target: number, stiffness: number, damping: number, dt: number) {429 spring.velocity += (target - spring.value) * stiffness * dt;430 spring.velocity *= Math.exp(-damping * dt);431 spring.value += spring.velocity * dt;432 return spring.value;433}434435export interface Button3DProps extends Pick<MaterialProps, "primaryColor">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {436 label: string;437 onClick?: () => void;438 primaryColor?: string;439 /** @deprecated Use `primaryColor`. */440 baseColor?: string;441 hoverColor?: string;442 /** Thickness of the key cap, in CSS pixels. Default 22. */443 depth?: number;444 /** How far the cap sinks when pressed, in CSS pixels. Default 14. */445 pressDistance?: number;446}447448/** State shared with the accessible DOM button (keyboard presses and focus ring). */449export interface ButtonExternalState {450 pressed: boolean;451 focused: boolean;452}453454const HEIGHT = 58;455const FONT_SIZE = 16;456const PADDING_X = 34;457const BEVEL = 5;458const SOCKET_MARGIN = 9;459460export interface Button3DSceneProps extends Button3DProps {461 /** Keyboard state from an accessible DOM button (optional when used inside your own scene). */462 external?: RefObject<ButtonExternalState>;463}464465/** The button's 3D content, for an existing R3F scene (1 world unit = 1 CSS pixel, see PixelPerspective). */466export const InteractiveButton3DScene = memo(function InteractiveButton3DScene({467 label,468 onClick,469 primaryColor,470 baseColor = primaryColor ?? "#6d28d9",471 hoverColor = "#8b5cf6",472 depth = 22,473 pressDistance = 14,474 external,475}: Button3DSceneProps) {476 const gl = useThree((state) => state.gl);477 const tiltRef = useRef<THREE.Group>(null);478 const capRef = useRef<THREE.Group>(null);479 const lightRef = useRef<THREE.PointLight>(null);480 const state = useRef({ hovered: false, pressed: false, pointerX: 0, pointerY: 0, hover: 0, focus: 0 });481 const press = useRef<Spring>({ value: 0, velocity: 0 });482 const colors = useMemo(() => ({ base: new THREE.Color(), hover: new THREE.Color() }), []);483 const onClickRef = useRef(onClick);484 useEffect(() => {485 onClickRef.current = onClick;486 });487488 const width = Math.ceil(measureLabel(label, FONT_SIZE, 600)) + PADDING_X * 2;489 const texture = useLabelTexture({ text: label, width, height: HEIGHT, color: "#ffffff", fontSize: FONT_SIZE, fontWeight: 600 });490491 const capGeometry = useMemo(() => createBevelledSlab(width, HEIGHT, HEIGHT / 2, depth, BEVEL), [width, depth]);492 const socketGeometry = useMemo(493 () => createBevelledSlab(width + SOCKET_MARGIN * 2, HEIGHT + SOCKET_MARGIN * 2, HEIGHT / 2 + SOCKET_MARGIN, depth * 0.6, 4),494 [width, depth]495 );496 const labelGeometry = useMemo(() => new THREE.PlaneGeometry(width, HEIGHT), [width]);497 const capMaterial = useMemo(() => new THREE.MeshPhysicalMaterial({ clearcoat: 1, clearcoatRoughness: 0.2, roughness: 0.35, metalness: 0.05 }), []);498 const socketMaterial = useMemo(() => new THREE.MeshStandardMaterial({ color: "#0c0c10", roughness: 0.55, metalness: 0.4 }), []);499 const labelMaterial = useMemo(() => new THREE.MeshBasicMaterial({ transparent: true, depthWrite: false, toneMapped: false }), []);500501 useEffect(() => {502 labelMaterial.map = texture;503 labelMaterial.needsUpdate = true;504 }, [labelMaterial, texture]);505 useEffect(() => {506 colors.base.set(baseColor);507 colors.hover.set(hoverColor);508 }, [colors, baseColor, hoverColor]);509 useEffect(510 () => () => {511 capGeometry.dispose();512 socketGeometry.dispose();513 labelGeometry.dispose();514 },515 [capGeometry, socketGeometry, labelGeometry]516 );517 useEffect(518 () => () => {519 capMaterial.dispose();520 socketMaterial.dispose();521 labelMaterial.dispose();522 },523 [capMaterial, socketMaterial, labelMaterial]524 );525526 useFrame((_, delta) => {527 const dt = Math.min(delta, 1 / 30);528 const s = state.current;529 const keyboard = external?.current;530 const isPressed = s.pressed || !!keyboard?.pressed;531532 // Press: the cap sinks on Z; release: an elastic rebound (damped spring, under-damped on purpose)533 stepSpring(press.current, isPressed ? -pressDistance : 0, 520, 15, dt);534 if (capRef.current) capRef.current.position.z = depth / 2 + press.current.value;535536 // Hover: color, glossier finish, and a highlight that follows the pointer across the cap537 s.hover = THREE.MathUtils.damp(s.hover, s.hovered || keyboard?.focused ? 1 : 0, 10, dt);538 capMaterial.color.copy(colors.base).lerp(colors.hover, s.hover);539 capMaterial.roughness = THREE.MathUtils.lerp(0.38, 0.12, s.hover);540 capMaterial.clearcoatRoughness = THREE.MathUtils.lerp(0.3, 0.04, s.hover);541 capMaterial.emissive.copy(colors.hover).multiplyScalar(s.hover * 0.12 + (keyboard?.focused ? 0.1 : 0));542 const light = lightRef.current;543 if (light) {544 light.intensity = s.hover * 2.4;545 light.position.x = THREE.MathUtils.damp(light.position.x, s.pointerX * width * 0.5, 12, dt);546 light.position.y = THREE.MathUtils.damp(light.position.y, s.pointerY * HEIGHT * 0.5, 12, dt);547 }548549 // Tilt towards the pointer550 const tilt = tiltRef.current;551 if (tilt) {552 tilt.rotation.y = THREE.MathUtils.damp(tilt.rotation.y, s.hovered ? s.pointerX * 0.22 : 0, 8, dt);553 tilt.rotation.x = THREE.MathUtils.damp(tilt.rotation.x, s.hovered ? -s.pointerY * 0.3 : 0, 8, dt);554 }555 });556557 const onPointerMove = (e: ThreeEvent<PointerEvent>) => {558 if (!tiltRef.current) return;559 const local = tiltRef.current.worldToLocal(e.point.clone());560 state.current.pointerX = THREE.MathUtils.clamp(local.x / (width / 2), -1, 1);561 state.current.pointerY = THREE.MathUtils.clamp(local.y / (HEIGHT / 2), -1, 1);562 };563564 return (565 <group ref={tiltRef}>566 {/* Socket: the cap's shadow falls into it */}567 <mesh geometry={socketGeometry} material={socketMaterial} position={[0, 0, -depth * 0.3]} receiveShadow />568 <group ref={capRef} position={[0, 0, depth / 2]}>569 <mesh570 geometry={capGeometry}571 material={capMaterial}572 castShadow573 onPointerOver={(e: ThreeEvent<PointerEvent>) => {574 e.stopPropagation();575 state.current.hovered = true;576 gl.domElement.style.cursor = "pointer";577 }}578 onPointerOut={() => {579 state.current.hovered = false;580 state.current.pressed = false;581 gl.domElement.style.cursor = "";582 }}583 onPointerMove={onPointerMove}584 onPointerDown={(e: ThreeEvent<PointerEvent>) => {585 e.stopPropagation();586 state.current.pressed = true;587 }}588 onPointerUp={(e: ThreeEvent<PointerEvent>) => {589 e.stopPropagation();590 // Released over the button: that's a click591 if (state.current.pressed) onClickRef.current?.();592 state.current.pressed = false;593 }}594 />595 <mesh geometry={labelGeometry} material={labelMaterial} position={[0, 0, depth / 2 + BEVEL + 0.5]} />596 <pointLight ref={lightRef} position={[0, 0, depth + 40]} intensity={0} distance={HEIGHT * 4} decay={0} />597 </group>598 </group>599 );600});601602/** Self-contained button: fills its positioned parent and centers the key. */603function InteractiveButton3D(props: Button3DProps) {604 const external = useRef<ButtonExternalState>({ pressed: false, focused: false });605 const [focused, setFocused] = useState(false);606 return (607 <>608 <UICanvas pauseWhenOffscreen={props.pauseWhenOffscreen} lowPowerMode={props.lowPowerMode} shadows>609 <PixelPerspective />610 <ambientLight intensity={0.55} />611 <directionalLight612 position={[-120, 220, 420]}613 intensity={2.2}614 castShadow615 shadow-mapSize={[1024, 1024]}616 shadow-bias={-0.0005}617 shadow-camera-left={-400}618 shadow-camera-right={400}619 shadow-camera-top={200}620 shadow-camera-bottom={-200}621 shadow-camera-near={10}622 shadow-camera-far={1200}623 />624 <Environment resolution={128} frames={1}>625 <Lightformer form="rect" intensity={2.5} position={[0, 5, 3]} rotation-x={Math.PI / 2} scale={[10, 2, 1]} />626 <Lightformer form="rect" intensity={1.2} position={[-5, 0, 3]} rotation-y={Math.PI / 2} scale={[2, 6, 1]} />627 </Environment>628 <InteractiveButton3DScene {...props} external={external} />629 </UICanvas>630 {/* Real button for keyboard and screen-reader users: drives the same press animation */}631 <button632 type="button"633 style={SR_ONLY}634 onClick={() => props.onClick?.()}635 onFocus={() => {636 external.current.focused = true;637 setFocused(true);638 }}639 onBlur={() => {640 external.current.focused = false;641 external.current.pressed = false;642 setFocused(false);643 }}644 onKeyDown={(e) => {645 if (e.key === "Enter" || e.key === " ") external.current.pressed = true;646 }}647 onKeyUp={() => {648 external.current.pressed = false;649 }}650 >651 {props.label}652 </button>653 {focused ? (654 <span aria-hidden="true" style={{ position: "absolute", inset: 4, borderRadius: 18, outline: "2px solid rgba(255,255,255,0.6)", pointerEvents: "none" }} />655 ) : null}656 </>657 );658}659660export default memo(InteractiveButton3D);
03
Drop it in a page
Updated live with the settings above.
app/page.tsx
1import InteractiveButton3D from "@/components/InteractiveButton3D";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 <InteractiveButton3D8 label="Get started"9 depth={22}10 pressDistance={14}11 primaryColor="#6d28d9"12 hoverColor="#8b5cf6"13 />14 </div>15 );16}