← All components Next componentHolographic Card→
Buttons · Button
Energy Portal Button
A dark button core wrapped in a plasma halo that speeds up and tightens on hover.
<EnergyPortalButton3D />Live
Hover to speed up the plasma
Customize
Aura#3000b3
Core#0b1020
Installation
Use it in your project
Or skip the copy-paste
One command: writes the file and installs the dependencies.
$ npx deepui-cli add energy-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/EnergyPortalButton3D.tsx and paste it in.
components/EnergyPortalButton3D.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 * Shared GLSL noise functions, injected into the background shaders as strings.20 *21 * Both are the classic webgl-noise implementations by Ian McEwan and Stefan22 * Gustavson (Ashima Arts), MIT License — https://github.com/ashima/webgl-noise23 */2425/** 3D simplex noise: `float snoise(vec3 v)`, returns roughly -1..1. */26const SIMPLEX_3D = /* glsl */ `27vec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }28vec4 mod289(vec4 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }29vec4 permute(vec4 x) { return mod289(((x * 34.0) + 10.0) * x); }30vec4 taylorInvSqrt(vec4 r) { return 1.79284291400159 - 0.85373472095314 * r; }3132float snoise(vec3 v) {33 const vec2 C = vec2(1.0 / 6.0, 1.0 / 3.0);34 const vec4 D = vec4(0.0, 0.5, 1.0, 2.0);3536 vec3 i = floor(v + dot(v, C.yyy));37 vec3 x0 = v - i + dot(i, C.xxx);3839 vec3 g = step(x0.yzx, x0.xyz);40 vec3 l = 1.0 - g;41 vec3 i1 = min(g.xyz, l.zxy);42 vec3 i2 = max(g.xyz, l.zxy);4344 vec3 x1 = x0 - i1 + C.xxx;45 vec3 x2 = x0 - i2 + C.yyy;46 vec3 x3 = x0 - D.yyy;4748 i = mod289(i);49 vec4 p = permute(permute(permute(50 i.z + vec4(0.0, i1.z, i2.z, 1.0))51 + i.y + vec4(0.0, i1.y, i2.y, 1.0))52 + i.x + vec4(0.0, i1.x, i2.x, 1.0));5354 float n_ = 0.142857142857;55 vec3 ns = n_ * D.wyz - D.xzx;5657 vec4 j = p - 49.0 * floor(p * ns.z * ns.z);58 vec4 x_ = floor(j * ns.z);59 vec4 y_ = floor(j - 7.0 * x_);6061 vec4 x = x_ * ns.x + ns.yyyy;62 vec4 y = y_ * ns.x + ns.yyyy;63 vec4 h = 1.0 - abs(x) - abs(y);6465 vec4 b0 = vec4(x.xy, y.xy);66 vec4 b1 = vec4(x.zw, y.zw);67 vec4 s0 = floor(b0) * 2.0 + 1.0;68 vec4 s1 = floor(b1) * 2.0 + 1.0;69 vec4 sh = -step(h, vec4(0.0));7071 vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;72 vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww;7374 vec3 p0 = vec3(a0.xy, h.x);75 vec3 p1 = vec3(a0.zw, h.y);76 vec3 p2 = vec3(a1.xy, h.z);77 vec3 p3 = vec3(a1.zw, h.w);7879 vec4 norm = taylorInvSqrt(vec4(dot(p0, p0), dot(p1, p1), dot(p2, p2), dot(p3, p3)));80 p0 *= norm.x;81 p1 *= norm.y;82 p2 *= norm.z;83 p3 *= norm.w;8485 vec4 m = max(0.5 - vec4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0);86 m = m * m;87 return 105.0 * dot(m * m, vec4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3)));88}89`;9091/**92 * The shared props API of DeepUI's individual 3D components (not the full-page templates, which keep93 * their own tailored scenes).94 *95 * The props are grouped by concern. A component extends ONLY the groups it really applies, so its96 * type never advertises a knob that does nothing (a card has no particles, a background has no tilt):97 *98 * interface MyCardProps extends CursorProps, TiltProps, MaterialProps, PerformanceProps { … }99 *100 * `Base3DComponentProps` is every group at once, for tooling that handles any component. Same name,101 * same unit and same meaning everywhere; the default values live in DEFAULT_3D_PROPS. These files are102 * inlined into each component's single-file bundle (lib/bundle-source.mjs), only what it uses.103 */104105/** Which rotation axes follow the pointer. "x-only": the object nods (up / down); "y-only": it turns (left / right). */106export type TiltAxis = "both" | "x-only" | "y-only" | "none";107108/** 1. Cursor: how the pointer pulls, pushes and drags the object. */109interface CursorProps {110 /** 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). */111 cursorRadius?: number;112 /** Positive pulls things towards the pointer, negative pushes them away (repulsion, shockwave). Default 1. */113 cursorForce?: number;114 /** How far the object slides towards the pointer, 0 (stays put) to 1 (follows closely). Default 0. */115 magneticStrength?: number;116 /** Share of the remaining distance the motion closes each frame (at 60 fps), 0.01 (heavy, slow) to 1 (instant). Default 0.1. */117 cursorDamping?: number;118}119120/** 2. Tilt and parallax: the object leans towards the pointer, its layers slide against each other. */121interface TiltProps {122 /** Largest lean towards the pointer, in degrees. Default 15. */123 maxTiltAngle?: number;124 /** Axes that follow the pointer. Default "both". */125 tiltAxis?: TiltAxis;126 /** Lean away from the pointer instead of towards it. Default false. */127 invertTilt?: boolean;128 /** How far apart the depth layers slide when the object tilts, 0 (flat) to 2. Default 1. */129 parallaxOffset?: number;130}131132/** 3. Text and 3D typography, for components that draw a label. */133interface Text3DProps {134 /** The label drawn by the component. */135 text?: string;136 /** Scale of the lettering. Default 1. */137 fontSize?: number;138 /** Extrusion depth of 3D letters. Default 0.2. */139 textDepth?: number;140 /** Bevelled, light-catching edges on 3D letters. Default true. */141 bevelEnabled?: boolean;142 /** Custom font: a .woff / .ttf (flat text) or a typeface .json (extruded text). */143 fontUrl?: string;144}145146/** 4. Rendering, materials and glow. */147interface MaterialProps {148 /** Main color of the object. Default "#6366f1". */149 primaryColor?: string;150 /** Color of the glow. Default "#00f0ff". */151 emissiveColor?: string;152 /** Strength of the glow, 0 (none) to 3. Default 1. */153 emissiveIntensity?: number;154 /** 0 (mirror, glass) to 1 (matte). Default 0.3. */155 roughness?: number;156 /** 0 (plastic, organic) to 1 (metal). Default 0.5. */157 metalness?: number;158 /** 0 (opaque) to 1 (clear glass): see-through, refracting surfaces. Default 0. */159 transmission?: number;160 /** Technical wireframe rendering. Default false. */161 wireframe?: boolean;162}163164/** 5. Particles, idle motion and shader animation. */165interface MotionProps {166 /** Number of instanced elements. Default depends on the component. */167 particleCount?: number;168 /** Spin on its own, in radians per second (negative: the other way; 0.5 ≈ one turn in 12 s). Default 0. */169 autoRotateSpeed?: number;170 /** Pulses or ripples per second. Default 1. */171 pulseRate?: number;172 /** Amplitude of the noise deformation, 0 (none) to 2. Default 1. */173 displacementScale?: number;174}175176/** 6. Environment and camera. */177interface EnvironmentProps {178 /** Camera field of view, in degrees. Default depends on the component. */179 cameraFov?: number;180 /** Color of the depth fog. Default "#0a0a0a". */181 fogColor?: string;182 /** Thickness of the fog, 0 (none) to 0.2. Default 0. */183 fogDensity?: number;184}185186/** 7. Performance and accessibility. */187interface PerformanceProps {188 /** Lighter rendering for weak devices: pixel ratio 1, fewer instances, smaller environment maps. Default false. */189 lowPowerMode?: boolean;190 /** Under the OS "reduce motion" setting, stop idle spin, pulses and deformation (pointer feedback stays). Default true. */191 respectReducedMotion?: boolean;192 /** Stop the render loop while the component is scrolled out of view. Default true. */193 pauseWhenOffscreen?: boolean;194}195196/** Every group at once. Components extend only the groups they apply (see the top of this file). */197interface Base3DComponentProps198 extends CursorProps,199 TiltProps,200 Text3DProps,201 MaterialProps,202 MotionProps,203 EnvironmentProps,204 PerformanceProps {}205206type Defaults = Required<Omit<Base3DComponentProps, "text" | "fontUrl" | "particleCount" | "cameraFov">>;207208/** The values a prop takes when it is left out. A component may override one, and then documents it. */209const DEFAULT_3D_PROPS: Defaults = {210 cursorRadius: 220,211 cursorForce: 1,212 magneticStrength: 0,213 cursorDamping: 0.1,214 maxTiltAngle: 15,215 tiltAxis: "both",216 invertTilt: false,217 parallaxOffset: 1,218 fontSize: 1,219 textDepth: 0.2,220 bevelEnabled: true,221 primaryColor: "#6366f1",222 emissiveColor: "#00f0ff",223 emissiveIntensity: 1,224 roughness: 0.3,225 metalness: 0.5,226 transmission: 0,227 wireframe: false,228 autoRotateSpeed: 0,229 pulseRate: 1,230 displacementScale: 1,231 fogColor: "#0a0a0a",232 fogDensity: 0,233 lowPowerMode: false,234 respectReducedMotion: true,235 pauseWhenOffscreen: true,236};237238/** Inline widget: fills its positioned parent and receives pointer events. */239const FILL_STYLE: CSSProperties = { position: "absolute", top: 0, left: 0, width: "100%", height: "100%" };240241/** Cursor overlay: covers the viewport, above everything, never intercepts the page's events. */242const OVERLAY_STYLE: CSSProperties = {243 position: "fixed",244 top: 0,245 left: 0,246 width: "100%",247 height: "100%",248 pointerEvents: "none",249 zIndex: 9999,250};251252/** Visually hidden but reachable by keyboard and screen readers. */253const SR_ONLY: CSSProperties = {254 position: "absolute",255 width: 1,256 height: 1,257 padding: 0,258 margin: -1,259 overflow: "hidden",260 clip: "rect(0, 0, 0, 0)",261 whiteSpace: "nowrap",262 border: 0,263};264265interface UICanvasProps extends Omit<CanvasProps, "children" | "style" | "gl">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {266 children: ReactNode;267 /** Full-viewport, click-through overlay (cursors) instead of an inline widget. */268 overlay?: boolean;269}270271/**272 * Ready-to-use <Canvas>: pauses its render loop while scrolled out of view (pauseWhenOffscreen), pixel273 * ratio 1 in lowPowerMode; R3F disposes the renderer and its WebGL context on unmount.274 */275function UICanvas({ children, overlay = false, dpr = [1, 2], pauseWhenOffscreen = DEFAULT_3D_PROPS.pauseWhenOffscreen, lowPowerMode = DEFAULT_3D_PROPS.lowPowerMode, ...canvasProps }: UICanvasProps) {276 const containerRef = useRef<HTMLDivElement>(null);277 // In view at first: the first frame is always drawn before the loop can be paused278 const [inView, setInView] = useState(true);279 useEffect(() => {280 const el = containerRef.current;281 if (!el || !pauseWhenOffscreen) return undefined;282 const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting));283 observer.observe(el);284 return () => observer.disconnect();285 }, [pauseWhenOffscreen]);286 return (287 <div ref={containerRef} style={overlay ? OVERLAY_STYLE : FILL_STYLE} aria-hidden="true">288 <Canvas289 dpr={lowPowerMode ? 1 : dpr}290 frameloop={inView || !pauseWhenOffscreen ? "always" : "never"}291 gl={{ antialias: true, alpha: true, powerPreference: "high-performance" }}292 style={overlay ? { pointerEvents: "none" } : undefined}293 {...canvasProps}294 >295 {children}296 </Canvas>297 </div>298 );299}300301/**302 * Perspective camera placed so that 1 world unit = 1 CSS pixel on the z = 0 plane: widgets are laid303 * out in pixels like the rest of the page, and still get real depth (presses, tilts, shadows).304 */305function PixelPerspective({ fov = 30 }: { fov?: number }) {306 const camera = useThree((state) => state.camera) as THREE.PerspectiveCamera;307 const size = useThree((state) => state.size);308 useLayoutEffect(() => {309 camera.fov = fov;310 camera.near = 1;311 camera.far = 20000;312 camera.position.set(0, 0, size.height / 2 / Math.tan(THREE.MathUtils.degToRad(fov / 2)));313 camera.lookAt(0, 0, 0);314 camera.updateProjectionMatrix();315 }, [camera, size, fov]);316 return null;317}318319function pageFontFamily() {320 if (typeof document === "undefined") return "sans-serif";321 return getComputedStyle(document.body).fontFamily || "sans-serif";322}323324let measureContext: CanvasRenderingContext2D | null = null;325326/** Width of a label in CSS pixels, in the page's font. */327function measureLabel(text: string, fontSize: number, fontWeight = 600) {328 if (typeof document === "undefined") return text.length * fontSize * 0.6;329 measureContext ??= document.createElement("canvas").getContext("2d");330 if (!measureContext) return text.length * fontSize * 0.6;331 measureContext.font = `${fontWeight} ${fontSize}px ${pageFontFamily()}`;332 return measureContext.measureText(text).width;333}334335interface LabelOptions {336 text: string;337 /** Second, smaller line under the text. */338 subtext?: string;339 /** Glyph drawn before the text (emoji, arrow, symbol…). */340 icon?: string;341 width: number;342 height: number;343 color: string;344 /** Face color; transparent when omitted. */345 background?: string;346 fontSize?: number;347 fontWeight?: number;348 /** Wrap the text over several lines within the width (minus padding). */349 wrap?: boolean;350 align?: "center" | "left";351 /** Horizontal padding, in CSS pixels (used by wrapping and left alignment). Default 0. */352 padding?: number;353 /** Line height, as a multiple of the font size. Default 1.35. */354 lineHeight?: number;355}356357function wrapLines(ctx: CanvasRenderingContext2D, text: string, maxWidth: number) {358 const lines: string[] = [];359 let line = "";360 for (const word of text.split(/\s+/)) {361 const candidate = line ? `${line} ${word}` : word;362 if (line && ctx.measureText(candidate).width > maxWidth) {363 lines.push(line);364 line = word;365 } else {366 line = candidate;367 }368 }369 if (line) lines.push(line);370 return lines;371}372373function drawLabel(canvas: HTMLCanvasElement, o: LabelOptions) {374 // Drawn at 2× (or the screen's ratio) so the text stays crisp once mapped on its plane375 const scale = Math.min(Math.max(window.devicePixelRatio || 1, 2), 3);376 canvas.width = Math.max(2, Math.ceil(o.width * scale));377 canvas.height = Math.max(2, Math.ceil(o.height * scale));378 const ctx = canvas.getContext("2d");379 if (!ctx) return;380 ctx.setTransform(scale, 0, 0, scale, 0, 0);381 ctx.clearRect(0, 0, o.width, o.height);382 if (o.background) {383 ctx.fillStyle = o.background;384 ctx.fillRect(0, 0, o.width, o.height);385 }386387 const family = pageFontFamily();388 const size = o.fontSize ?? 15;389 const weight = o.fontWeight ?? 600;390 ctx.fillStyle = o.color;391 ctx.textBaseline = "middle";392 ctx.textAlign = "center";393394 const padding = o.padding ?? 0;395 const left = o.align === "left";396 ctx.textAlign = left ? "left" : "center";397 const x = left ? padding : o.width / 2;398399 let text = o.text;400 if (o.icon) text = `${o.icon} ${text}`;401 ctx.font = `${weight} ${size}px ${family}`;402403 if (o.wrap) {404 const step = size * (o.lineHeight ?? 1.35);405 const lines = wrapLines(ctx, text, o.width - padding * 2);406 // Only as many lines as fit; the last one kept ends with an ellipsis407 const maxLines = Math.max(1, Math.floor(o.height / step));408 if (lines.length > maxLines) {409 lines.length = maxLines;410 let last = lines[maxLines - 1];411 while (last && ctx.measureText(`${last}…`).width > o.width - padding * 2) last = last.slice(0, -1);412 lines[maxLines - 1] = `${last.trimEnd()}…`;413 }414 const top = o.height / 2 - ((lines.length - 1) * step) / 2;415 lines.forEach((line, i) => ctx.fillText(line, x, top + i * step));416 return;417 }418419 const mainY = o.subtext ? o.height * 0.4 : o.height / 2;420 ctx.fillText(text, x, mainY);421422 if (o.subtext) {423 ctx.globalAlpha = 0.7;424 ctx.font = `500 ${Math.round(size * 0.72)}px ${family}`;425 ctx.fillText(o.subtext, x, o.height * 0.7);426 ctx.globalAlpha = 1;427 }428}429430/**431 * Text drawn into a CanvasTexture, in the page's own font: no font file to download (unlike drei's432 * <Text>). Redrawn once web fonts finish loading; disposed on unmount.433 */434function useLabelTexture(options: LabelOptions) {435 const key = JSON.stringify(options);436 const [fontsVersion, setFontsVersion] = useState(0);437 useEffect(() => {438 let alive = true;439 document.fonts?.ready.then(() => {440 if (alive) setFontsVersion((v) => v + 1);441 });442 return () => {443 alive = false;444 };445 }, []);446447 const texture = useMemo(() => {448 const t = new THREE.CanvasTexture(document.createElement("canvas"));449 t.colorSpace = THREE.SRGBColorSpace;450 t.anisotropy = 4;451 return t;452 }, []);453454 useLayoutEffect(() => {455 drawLabel(texture.image as HTMLCanvasElement, JSON.parse(key) as LabelOptions);456 texture.needsUpdate = true;457 }, [texture, key, fontsVersion]);458459 useEffect(() => () => texture.dispose(), [texture]);460 return texture;461}462463/** Rounded-rectangle outline centered on the origin (radius clamped to a pill). */464function roundedRectShape(width: number, height: number, radius: number) {465 const r = Math.min(radius, width / 2, height / 2);466 const x = -width / 2;467 const y = -height / 2;468 const shape = new THREE.Shape();469 shape.moveTo(x + r, y);470 shape.lineTo(x + width - r, y);471 shape.quadraticCurveTo(x + width, y, x + width, y + r);472 shape.lineTo(x + width, y + height - r);473 shape.quadraticCurveTo(x + width, y + height, x + width - r, y + height);474 shape.lineTo(x + r, y + height);475 shape.quadraticCurveTo(x, y + height, x, y + height - r);476 shape.lineTo(x, y + r);477 shape.quadraticCurveTo(x, y, x + r, y);478 return shape;479}480481/** Bevelled, extruded rounded rectangle, centered on the origin (front face at +depth/2 + bevel). */482function createBevelledSlab(width: number, height: number, radius: number, depth: number, bevel: number) {483 const geometry = new THREE.ExtrudeGeometry(roundedRectShape(width - bevel * 2, height - bevel * 2, Math.max(0, radius - bevel)), {484 depth,485 bevelEnabled: true,486 bevelThickness: bevel,487 bevelSize: bevel,488 bevelSegments: 6,489 curveSegments: 24,490 });491 geometry.translate(0, 0, -depth / 2);492 return geometry;493}494495/** State shared with the accessible DOM button (keyboard presses and focus ring). */496interface ButtonExternalState {497 pressed: boolean;498 focused: boolean;499}500501export interface EnergyButtonProps extends Pick<MaterialProps, "emissiveColor" | "primaryColor">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {502 label: string;503 onClick?: () => void;504 /** Color of the plasma halo. */505 emissiveColor?: string;506 /** @deprecated Use `emissiveColor`. */507 auraColor?: string;508 /** Color of the button's core. */509 primaryColor?: string;510 /** @deprecated Use `primaryColor`. */511 coreColor?: string;512 /** Flow speed multiplier. Default 1. */513 speed?: number;514}515516const HEIGHT = 60;517const FONT_SIZE = 16;518const PADDING_X = 38;519const DEPTH = 12;520const BEVEL = 5;521const AURA_MARGIN = 90; // halo extent around the button, in CSS pixels522523const auraVertexShader = /* glsl */ `524varying vec2 vUv;525void main() {526 vUv = uv;527 gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);528}529`;530531const auraFragmentShader = /* glsl */ `532uniform vec2 uButton; // button size, px533uniform vec2 uPlane; // aura plane size, px534uniform float uTime; // flow time (accelerates on hover)535uniform float uHover; // 0 → 1536uniform float uPulse; // 0 → 1 shockwave after a click (1 = idle)537uniform vec3 uColor;538varying vec2 vUv;539540${SIMPLEX_3D}541542float sdRoundBox(vec2 p, vec2 halfSize, float r) {543 vec2 q = abs(p) - halfSize + r;544 return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - r;545}546547void main() {548 vec2 p = (vUv - 0.5) * uPlane;549 float d = sdRoundBox(p, uButton * 0.5, uButton.y * 0.5); // 0 on the outline, > 0 outside550 if (d < -2.0) discard;551552 // Angle around the button, turning continuously (faster on hover)553 float angle = atan(p.y, p.x) + uTime * 0.35;554 // Noise on a circle (cos/sin of the angle): seamless all the way around. The radial coordinate555 // scrolls with time, so the plasma flows towards the outline; on hover it converges much faster.556 vec3 q = vec3(cos(angle) * 1.6, sin(angle) * 1.6, d * 0.035 + uTime * (0.25 + uHover * 1.2));557 float n = snoise(q);558 float tendrils = pow(1.0 - abs(n), 7.0);559 float swirl = snoise(q * 2.3 + 7.0) * 0.5 + 0.5;560561 float reach = mix(26.0, 16.0, uHover); // the halo tightens around the button on hover562 float glow = exp(-max(d, 0.0) / reach);563 float rim = exp(-abs(d) / 2.5); // thin bright line on the outline564 float intensity = glow * (0.25 + tendrils * (1.3 + uHover * 1.2) + swirl * 0.25) + rim * (0.7 + uHover * 0.6);565566 // Click shockwave: a ring racing outwards567 float wave = exp(-abs(d - uPulse * ${AURA_MARGIN.toFixed(1)}) / 5.0) * (1.0 - uPulse);568 intensity += wave * 1.6;569570 // Fade before the plane's edges so its square outline never shows571 float edge = 1.0 - smoothstep(${(AURA_MARGIN * 0.6).toFixed(1)}, ${(AURA_MARGIN * 0.95).toFixed(1)}, d);572 intensity *= edge;573574 vec3 color = uColor * intensity + vec3(1.0) * pow(intensity, 3.0) * 0.25;575 gl_FragColor = vec4(color, clamp(intensity, 0.0, 1.0));576 #include <colorspace_fragment>577}578`;579580export interface EnergyButtonSceneProps extends EnergyButtonProps {581 /** Keyboard state from an accessible DOM button (optional when used inside your own scene). */582 external?: RefObject<ButtonExternalState>;583}584585/** The button's 3D content, for an existing R3F scene (1 world unit = 1 CSS pixel, see PixelPerspective). */586export const EnergyPortalButton3DScene = memo(function EnergyPortalButton3DScene({587 label,588 onClick,589 emissiveColor,590 auraColor = emissiveColor ?? "#22d3ee",591 primaryColor,592 coreColor = primaryColor ?? "#0b1020",593 speed = 1,594 external,595}: EnergyButtonSceneProps) {596 const gl = useThree((state) => state.gl);597 const groupRef = useRef<THREE.Group>(null);598 const state = useRef({ hovered: false, pressed: false, pointerX: 0, pointerY: 0, hover: 0, flow: 0, pulse: 1, press: 0 });599 const onClickRef = useRef(onClick);600 useEffect(() => {601 onClickRef.current = onClick;602 });603604 const width = Math.ceil(measureLabel(label, FONT_SIZE, 600)) + PADDING_X * 2;605 const texture = useLabelTexture({ text: label, width, height: HEIGHT, color: "#ffffff", fontSize: FONT_SIZE, fontWeight: 600 });606607 const coreGeometry = useMemo(() => createBevelledSlab(width, HEIGHT, HEIGHT / 2, DEPTH, BEVEL), [width]);608 const auraGeometry = useMemo(() => new THREE.PlaneGeometry(width + AURA_MARGIN * 2, HEIGHT + AURA_MARGIN * 2), [width]);609 const labelGeometry = useMemo(() => new THREE.PlaneGeometry(width, HEIGHT), [width]);610 const coreMaterial = useMemo(() => new THREE.MeshPhysicalMaterial({ metalness: 0.3, roughness: 0.25, clearcoat: 1, clearcoatRoughness: 0.1 }), []);611 const labelMaterial = useMemo(() => new THREE.MeshBasicMaterial({ transparent: true, depthWrite: false, toneMapped: false }), []);612 const auraMaterial = useMemo(613 () =>614 new THREE.ShaderMaterial({615 uniforms: {616 uButton: { value: new THREE.Vector2() },617 uPlane: { value: new THREE.Vector2() },618 uTime: { value: 0 },619 uHover: { value: 0 },620 uPulse: { value: 1 },621 uColor: { value: new THREE.Color() },622 },623 vertexShader: auraVertexShader,624 fragmentShader: auraFragmentShader,625 transparent: true,626 depthWrite: false,627 blending: THREE.AdditiveBlending,628 }),629 []630 );631632 useEffect(() => {633 labelMaterial.map = texture;634 labelMaterial.needsUpdate = true;635 }, [labelMaterial, texture]);636 useEffect(() => {637 coreMaterial.color.set(coreColor);638 coreMaterial.emissive.set(auraColor);639 (auraMaterial.uniforms.uColor.value as THREE.Color).set(auraColor);640 (auraMaterial.uniforms.uButton.value as THREE.Vector2).set(width, HEIGHT);641 (auraMaterial.uniforms.uPlane.value as THREE.Vector2).set(width + AURA_MARGIN * 2, HEIGHT + AURA_MARGIN * 2);642 }, [coreMaterial, auraMaterial, coreColor, auraColor, width]);643 useEffect(644 () => () => {645 coreGeometry.dispose();646 auraGeometry.dispose();647 labelGeometry.dispose();648 },649 [coreGeometry, auraGeometry, labelGeometry]650 );651 useEffect(652 () => () => {653 coreMaterial.dispose();654 labelMaterial.dispose();655 auraMaterial.dispose();656 },657 [coreMaterial, labelMaterial, auraMaterial]658 );659660 useFrame((_, delta) => {661 const dt = Math.min(delta, 1 / 30);662 const s = state.current;663 const keyboard = external?.current;664 const engaged = s.hovered || !!keyboard?.focused;665666 // Flow: continuous rotation, accelerating on hover667 s.hover = THREE.MathUtils.damp(s.hover, engaged ? 1 : 0, 6, dt);668 s.flow += dt * speed * (1 + s.hover * 2.5);669 s.pulse = Math.min(1, s.pulse + dt * 1.4);670 const u = auraMaterial.uniforms;671 u.uTime.value = s.flow;672 u.uHover.value = s.hover;673 u.uPulse.value = s.pulse;674 coreMaterial.emissiveIntensity = 0.06 + s.hover * 0.18;675676 // Press: a slight scale-down; tilt towards the pointer677 s.press = THREE.MathUtils.damp(s.press, s.pressed || keyboard?.pressed ? 1 : 0, 18, dt);678 const group = groupRef.current;679 if (group) {680 group.scale.setScalar(1 - s.press * 0.05);681 group.rotation.y = THREE.MathUtils.damp(group.rotation.y, s.hovered ? s.pointerX * 0.2 : 0, 8, dt);682 group.rotation.x = THREE.MathUtils.damp(group.rotation.x, s.hovered ? -s.pointerY * 0.28 : 0, 8, dt);683 }684 });685686 const fire = () => {687 state.current.pulse = 0;688 onClickRef.current?.();689 };690691 return (692 <group ref={groupRef}>693 <mesh geometry={auraGeometry} material={auraMaterial} position={[0, 0, -DEPTH]} />694 <mesh695 geometry={coreGeometry}696 material={coreMaterial}697 onPointerOver={(e: ThreeEvent<PointerEvent>) => {698 e.stopPropagation();699 state.current.hovered = true;700 gl.domElement.style.cursor = "pointer";701 }}702 onPointerOut={() => {703 state.current.hovered = false;704 state.current.pressed = false;705 gl.domElement.style.cursor = "";706 }}707 onPointerMove={(e: ThreeEvent<PointerEvent>) => {708 if (!groupRef.current) return;709 const local = groupRef.current.worldToLocal(e.point.clone());710 state.current.pointerX = THREE.MathUtils.clamp(local.x / (width / 2), -1, 1);711 state.current.pointerY = THREE.MathUtils.clamp(local.y / (HEIGHT / 2), -1, 1);712 }}713 onPointerDown={(e: ThreeEvent<PointerEvent>) => {714 e.stopPropagation();715 state.current.pressed = true;716 }}717 onPointerUp={(e: ThreeEvent<PointerEvent>) => {718 e.stopPropagation();719 if (state.current.pressed) fire();720 state.current.pressed = false;721 }}722 />723 <mesh geometry={labelGeometry} material={labelMaterial} position={[0, 0, DEPTH / 2 + BEVEL + 0.5]} />724 </group>725 );726});727728/** Self-contained button: fills its positioned parent (leave ~90px around it for the halo) and centers it. */729function EnergyPortalButton3D(props: EnergyButtonProps) {730 const external = useRef<ButtonExternalState>({ pressed: false, focused: false });731 const [focused, setFocused] = useState(false);732 return (733 <>734 <UICanvas pauseWhenOffscreen={props.pauseWhenOffscreen} lowPowerMode={props.lowPowerMode}>735 <PixelPerspective />736 <ambientLight intensity={0.5} />737 <directionalLight position={[-120, 220, 420]} intensity={1.6} />738 <Environment resolution={128} frames={1}>739 <Lightformer form="rect" intensity={2.5} position={[0, 5, 3]} rotation-x={Math.PI / 2} scale={[10, 2, 1]} />740 <Lightformer form="rect" intensity={1.2} position={[5, 0, 3]} rotation-y={-Math.PI / 2} scale={[2, 6, 1]} />741 </Environment>742 <EnergyPortalButton3DScene {...props} external={external} />743 </UICanvas>744 {/* Real button for keyboard and screen-reader users: drives the same hover/press animation */}745 <button746 type="button"747 style={SR_ONLY}748 onClick={() => props.onClick?.()}749 onFocus={() => {750 external.current.focused = true;751 setFocused(true);752 }}753 onBlur={() => {754 external.current.focused = false;755 external.current.pressed = false;756 setFocused(false);757 }}758 onKeyDown={(e) => {759 if (e.key === "Enter" || e.key === " ") external.current.pressed = true;760 }}761 onKeyUp={() => {762 external.current.pressed = false;763 }}764 >765 {props.label}766 </button>767 {focused ? (768 <span aria-hidden="true" style={{ position: "absolute", inset: 4, borderRadius: 18, outline: "2px solid rgba(255,255,255,0.6)", pointerEvents: "none" }} />769 ) : null}770 </>771 );772}773774export default memo(EnergyPortalButton3D);
03
Drop it in a page
Updated live with the settings above.
app/page.tsx
1import EnergyPortalButton3D from "@/components/EnergyPortalButton3D";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 <EnergyPortalButton3D8 label="Enter the portal"9 speed={1}10 emissiveColor="#3000b3"11 primaryColor="#0b1020"12 />13 </div>14 );15}