Loading…
← All components

Widgets · Social proof

Security Badge

An access badge on a lanyard that swings with the pointer, with gold foil for VIPs, a photo and a colour-shifting security hologram.

<SecurityBadge3D />Live

Customize

Card#0f172a

Installation

Use it in your project

Or skip the copy-paste

One command: writes the file and installs the dependencies.

$ npx deepui-cli add security-badge
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/SecurityBadge3D.tsx and paste it in.

components/SecurityBadge3D.tsx
1"use client";
2
3import {
4 memo,
5 useEffect,
6 useMemo,
7 useRef,
8 useState,
9 type CSSProperties,
10 type DependencyList,
11 type ReactNode,
12} from "react";
13import * as THREE from "three";
14import { Canvas, useFrame, useThree, type CanvasProps } from "@react-three/fiber";
15import { Environment, Lightformer, RoundedBox } from "@react-three/drei";
16
17/**
18 * The shared props API of DeepUI's individual 3D components (not the full-page templates, which keep
19 * their own tailored scenes).
20 *
21 * The props are grouped by concern. A component extends ONLY the groups it really applies, so its
22 * type never advertises a knob that does nothing (a card has no particles, a background has no tilt):
23 *
24 * interface MyCardProps extends CursorProps, TiltProps, MaterialProps, PerformanceProps { … }
25 *
26 * `Base3DComponentProps` is every group at once, for tooling that handles any component. Same name,
27 * same unit and same meaning everywhere; the default values live in DEFAULT_3D_PROPS. These files are
28 * inlined into each component's single-file bundle (lib/bundle-source.mjs), only what it uses.
29 */
30
31/** Which rotation axes follow the pointer. "x-only": the object nods (up / down); "y-only": it turns (left / right). */
32export type TiltAxis = "both" | "x-only" | "y-only" | "none";
33
34/** 1. Cursor: how the pointer pulls, pushes and drags the object. */
35interface CursorProps {
36 /** 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). */
37 cursorRadius?: number;
38 /** Positive pulls things towards the pointer, negative pushes them away (repulsion, shockwave). Default 1. */
39 cursorForce?: number;
40 /** How far the object slides towards the pointer, 0 (stays put) to 1 (follows closely). Default 0. */
41 magneticStrength?: number;
42 /** Share of the remaining distance the motion closes each frame (at 60 fps), 0.01 (heavy, slow) to 1 (instant). Default 0.1. */
43 cursorDamping?: number;
44}
45
46/** 2. Tilt and parallax: the object leans towards the pointer, its layers slide against each other. */
47interface TiltProps {
48 /** Largest lean towards the pointer, in degrees. Default 15. */
49 maxTiltAngle?: number;
50 /** Axes that follow the pointer. Default "both". */
51 tiltAxis?: TiltAxis;
52 /** Lean away from the pointer instead of towards it. Default false. */
53 invertTilt?: boolean;
54 /** How far apart the depth layers slide when the object tilts, 0 (flat) to 2. Default 1. */
55 parallaxOffset?: number;
56}
57
58/** 3. Text and 3D typography, for components that draw a label. */
59interface Text3DProps {
60 /** The label drawn by the component. */
61 text?: string;
62 /** Scale of the lettering. Default 1. */
63 fontSize?: number;
64 /** Extrusion depth of 3D letters. Default 0.2. */
65 textDepth?: number;
66 /** Bevelled, light-catching edges on 3D letters. Default true. */
67 bevelEnabled?: boolean;
68 /** Custom font: a .woff / .ttf (flat text) or a typeface .json (extruded text). */
69 fontUrl?: string;
70}
71
72/** 4. Rendering, materials and glow. */
73interface MaterialProps {
74 /** Main color of the object. Default "#6366f1". */
75 primaryColor?: string;
76 /** Color of the glow. Default "#00f0ff". */
77 emissiveColor?: string;
78 /** Strength of the glow, 0 (none) to 3. Default 1. */
79 emissiveIntensity?: number;
80 /** 0 (mirror, glass) to 1 (matte). Default 0.3. */
81 roughness?: number;
82 /** 0 (plastic, organic) to 1 (metal). Default 0.5. */
83 metalness?: number;
84 /** 0 (opaque) to 1 (clear glass): see-through, refracting surfaces. Default 0. */
85 transmission?: number;
86 /** Technical wireframe rendering. Default false. */
87 wireframe?: boolean;
88}
89
90/** 5. Particles, idle motion and shader animation. */
91interface MotionProps {
92 /** Number of instanced elements. Default depends on the component. */
93 particleCount?: number;
94 /** Spin on its own, in radians per second (negative: the other way; 0.5 ≈ one turn in 12 s). Default 0. */
95 autoRotateSpeed?: number;
96 /** Pulses or ripples per second. Default 1. */
97 pulseRate?: number;
98 /** Amplitude of the noise deformation, 0 (none) to 2. Default 1. */
99 displacementScale?: number;
100}
101
102/** 6. Environment and camera. */
103interface EnvironmentProps {
104 /** Camera field of view, in degrees. Default depends on the component. */
105 cameraFov?: number;
106 /** Color of the depth fog. Default "#0a0a0a". */
107 fogColor?: string;
108 /** Thickness of the fog, 0 (none) to 0.2. Default 0. */
109 fogDensity?: number;
110}
111
112/** 7. Performance and accessibility. */
113interface PerformanceProps {
114 /** Lighter rendering for weak devices: pixel ratio 1, fewer instances, smaller environment maps. Default false. */
115 lowPowerMode?: boolean;
116 /** Under the OS "reduce motion" setting, stop idle spin, pulses and deformation (pointer feedback stays). Default true. */
117 respectReducedMotion?: boolean;
118 /** Stop the render loop while the component is scrolled out of view. Default true. */
119 pauseWhenOffscreen?: boolean;
120}
121
122/** Every group at once. Components extend only the groups they apply (see the top of this file). */
123interface Base3DComponentProps
124 extends CursorProps,
125 TiltProps,
126 Text3DProps,
127 MaterialProps,
128 MotionProps,
129 EnvironmentProps,
130 PerformanceProps {}
131
132type Defaults = Required<Omit<Base3DComponentProps, "text" | "fontUrl" | "particleCount" | "cameraFov">>;
133
134/** The values a prop takes when it is left out. A component may override one, and then documents it. */
135const DEFAULT_3D_PROPS: Defaults = {
136 cursorRadius: 220,
137 cursorForce: 1,
138 magneticStrength: 0,
139 cursorDamping: 0.1,
140 maxTiltAngle: 15,
141 tiltAxis: "both",
142 invertTilt: false,
143 parallaxOffset: 1,
144 fontSize: 1,
145 textDepth: 0.2,
146 bevelEnabled: true,
147 primaryColor: "#6366f1",
148 emissiveColor: "#00f0ff",
149 emissiveIntensity: 1,
150 roughness: 0.3,
151 metalness: 0.5,
152 transmission: 0,
153 wireframe: false,
154 autoRotateSpeed: 0,
155 pulseRate: 1,
156 displacementScale: 1,
157 fogColor: "#0a0a0a",
158 fogDensity: 0,
159 lowPowerMode: false,
160 respectReducedMotion: true,
161 pauseWhenOffscreen: true,
162};
163
164/** Fills the positioned parent. The objects receive pointer events (orbit, hover, click). */
165const FILL_STYLE: CSSProperties = { position: "absolute", top: 0, left: 0, width: "100%", height: "100%" };
166
167interface ObjectCanvasProps extends Omit<CanvasProps, "children" | "style" | "frameloop" | "gl">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {
168 children: ReactNode;
169 /** CSS touch-action of the canvas: "pan-y" keeps vertical page scrolling on touch screens. */
170 touchAction?: CSSProperties["touchAction"];
171}
172
173/**
174 * Ready-to-use <Canvas> shared by every object: fills its positioned parent, pauses its render loop
175 * while scrolled out of view, caps the pixel ratio; R3F disposes the renderer on unmount.
176 */
177function ObjectCanvas({ children, touchAction = "pan-y", dpr = [1, 2], shadows, pauseWhenOffscreen = DEFAULT_3D_PROPS.pauseWhenOffscreen, lowPowerMode = DEFAULT_3D_PROPS.lowPowerMode, ...canvasProps }: ObjectCanvasProps) {
178 const containerRef = useRef<HTMLDivElement>(null);
179 const [inView, setInView] = useState(true);
180
181 useEffect(() => {
182 const el = containerRef.current;
183 if (!el) return undefined;
184 const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting));
185 observer.observe(el);
186 return () => observer.disconnect();
187 }, []);
188
189 return (
190 <div ref={containerRef} style={FILL_STYLE}>
191 <Canvas
192 dpr={lowPowerMode ? 1 : dpr}
193 frameloop={inView || !pauseWhenOffscreen ? "always" : "never"}
194 gl={{ antialias: true, alpha: true, powerPreference: "high-performance" }}
195 style={{ touchAction }}
196 // `shadows` alone asks R3F for PCFSoftShadowMap, which recent three.js versions removed (with a warning)
197 shadows={shadows === true ? "percentage" : shadows}
198 {...canvasProps}
199 >
200 {children}
201 </Canvas>
202 </div>
203 );
204}
205
206/** Studio reflections from light panels: no HDR file to download. */
207function StudioEnvironment({ intensity = 1, warm = false }: { intensity?: number; warm?: boolean }) {
208 return (
209 <Environment resolution={256} frames={1}>
210 <Lightformer form="rect" intensity={3 * intensity} position={[0, 5, 2]} rotation-x={Math.PI / 2} scale={[10, 3, 1]} />
211 <Lightformer
212 form="rect"
213 intensity={2 * intensity}
214 position={[-5, 1, 2]}
215 rotation-y={Math.PI / 2}
216 scale={[2, 6, 1]}
217 color={warm ? "#ffe2c4" : "#ffffff"}
218 />
219 <Lightformer
220 form="rect"
221 intensity={1.5 * intensity}
222 position={[5, 0, -2]}
223 rotation-y={-Math.PI / 2}
224 scale={[2, 6, 1]}
225 color={warm ? "#c4dcff" : "#ffffff"}
226 />
227 <Lightformer form="ring" intensity={2 * intensity} position={[2, 3, 5]} scale={2} />
228 </Environment>
229 );
230}
231
232type Disposable = { dispose: () => void };
233
234type DisposableTree = Disposable | Disposable[] | { [key: string]: DisposableTree };
235
236function disposeTree(value: DisposableTree) {
237 if (Array.isArray(value)) value.forEach(disposeTree);
238 else if (typeof (value as Disposable).dispose === "function") (value as Disposable).dispose();
239 else Object.values(value as Record<string, DisposableTree>).forEach(disposeTree);
240}
241
242/**
243 * useMemo for GPU resources: the geometries/materials/textures it returns (alone, in an array or
244 * in a nested object) are disposed when the deps change and on unmount.
245 */
246function useDisposable<T extends DisposableTree>(factory: () => T, deps: DependencyList): T {
247 const value = useMemo(factory, deps);
248 useEffect(() => () => disposeTree(value), [value]);
249 return value;
250}
251
252const UP = new THREE.Vector3(0, 1, 0);
253
254/** Places a unit-height, Y-aligned mesh (e.g. a CylinderGeometry of height 1) between two points. */
255function stretchBetween(object: THREE.Object3D, from: THREE.Vector3, to: THREE.Vector3, scratch: THREE.Vector3) {
256 scratch.subVectors(to, from);
257 const length = scratch.length();
258 object.position.copy(from).addScaledVector(scratch, 0.5);
259 object.quaternion.setFromUnitVectors(UP, scratch.divideScalar(length || 1));
260 object.scale.y = length;
261 return length;
262}
263
264/**
265 * Keeps the object in frame on narrow canvases: when the aspect ratio drops below `minAspect`, the
266 * camera backs away from `target` (the orbit target, if controls are set) proportionally. It only
267 * acts when the canvas is resized, so it never fights the user's own orbiting.
268 */
269function ResponsiveCamera({ minAspect, target = [0, 0, 0] }: { minAspect: number; target?: [number, number, number] }) {
270 const camera = useThree((state) => state.camera);
271 const size = useThree((state) => state.size);
272 const controls = useThree((state) => state.controls) as { target?: THREE.Vector3; update?: () => void } | null;
273 const base = useRef<THREE.Vector3 | null>(null);
274
275 useEffect(() => {
276 const center = controls?.target ?? new THREE.Vector3(...target);
277 // The offset the scene was designed with, captured once
278 if (!base.current) base.current = camera.position.clone().sub(center);
279 const factor = Math.max(1, minAspect / (size.width / Math.max(size.height, 1)));
280 camera.position.copy(center).addScaledVector(base.current, factor);
281 controls?.update?.();
282 // `target` is read once with the base offset; an inline array would otherwise re-run this every render
283 }, [size.width, size.height, camera, controls, minAspect]);
284
285 return null;
286}
287
288/** Rounded rectangle with UVs normalized to 0–1, for printing a texture edge to edge. */
289function roundedPlane(width: number, height: number, radius: number) {
290 const s = new THREE.Shape();
291 const x = -width / 2;
292 const y = -height / 2;
293 s.moveTo(x + radius, y);
294 s.lineTo(x + width - radius, y);
295 s.quadraticCurveTo(x + width, y, x + width, y + radius);
296 s.lineTo(x + width, y + height - radius);
297 s.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
298 s.lineTo(x + radius, y + height);
299 s.quadraticCurveTo(x, y + height, x, y + height - radius);
300 s.lineTo(x, y + radius);
301 s.quadraticCurveTo(x, y, x + radius, y);
302 const g = new THREE.ShapeGeometry(s, 12);
303 const pos = g.attributes.position;
304 const uv = g.attributes.uv;
305 for (let i = 0; i < pos.count; i++) uv.setXY(i, (pos.getX(i) - x) / width, (pos.getY(i) - y) / height);
306 return g;
307}
308
309export interface SecurityBadgeProps extends Pick<MaterialProps, "primaryColor">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {
310 userName: string;
311 role: string;
312 /** Photo shown on the badge (same-origin or CORS-enabled). Initials are drawn without it. */
313 avatarUrl?: string;
314 /** Background of the card. Default "#0f172a". */
315 primaryColor?: string;
316 /** @deprecated Use `primaryColor`. */
317 badgeColor?: string;
318 /** Gold foil rim, gold chip and a "VIP ACCESS" band. Default false. */
319 isVIP?: boolean;
320}
321
322const CARD = { width: 2.1, height: 3.2, depth: 0.06 };
323const TEX = { width: 600, height: 914 };
324/** The lanyard clip: the card swings around it. */
325const PIVOT = new THREE.Vector3(0, 1.75, 0);
326
327/* -------------------------------------------------------------------------- */
328/* Card face */
329/* -------------------------------------------------------------------------- */
330
331const initials = (name: string) =>
332 name
333 .split(/\s+/)
334 .filter(Boolean)
335 .slice(0, 2)
336 .map((w) => w[0]!.toUpperCase())
337 .join("");
338
339/** Draws the printed face of the badge: header, photo, name, role, access band and barcode. */
340function drawFace(ctx: CanvasRenderingContext2D, { userName, role, badgeColor, isVIP }: Required<Omit<SecurityBadgeProps, "primaryColor" | "pauseWhenOffscreen" | "lowPowerMode" | "avatarUrl">>, avatar: HTMLImageElement | null) {
341 const { width: W, height: H } = TEX;
342 const gold = "#e7c27a";
343 const accent = isVIP ? gold : "#93c5fd";
344
345 // Background with a soft diagonal sheen
346 ctx.fillStyle = badgeColor;
347 ctx.fillRect(0, 0, W, H);
348 const sheen = ctx.createLinearGradient(0, 0, W, H);
349 sheen.addColorStop(0, "rgba(255,255,255,0.10)");
350 sheen.addColorStop(0.5, "rgba(255,255,255,0)");
351 sheen.addColorStop(1, "rgba(0,0,0,0.25)");
352 ctx.fillStyle = sheen;
353 ctx.fillRect(0, 0, W, H);
354
355 // Lanyard slot
356 ctx.fillStyle = "rgba(0,0,0,0.45)";
357 ctx.beginPath();
358 ctx.roundRect(W / 2 - 70, 34, 140, 22, 11);
359 ctx.fill();
360
361 // Header
362 ctx.textAlign = "center";
363 ctx.textBaseline = "middle";
364 ctx.fillStyle = "rgba(255,255,255,0.55)";
365 ctx.font = "600 24px ui-monospace, monospace";
366 ctx.fillText("D E E P U I · A C C E S S", W / 2, 104);
367
368 // Photo (or initials) in a ring
369 const cx = W / 2;
370 const cy = 330;
371 const r = 138;
372 ctx.save();
373 ctx.beginPath();
374 ctx.arc(cx, cy, r, 0, Math.PI * 2);
375 ctx.closePath();
376 ctx.clip();
377 if (avatar) {
378 const scale = Math.max((2 * r) / avatar.width, (2 * r) / avatar.height);
379 const w = avatar.width * scale;
380 const h = avatar.height * scale;
381 ctx.drawImage(avatar, cx - w / 2, cy - h / 2, w, h);
382 } else {
383 const g = ctx.createLinearGradient(cx - r, cy - r, cx + r, cy + r);
384 g.addColorStop(0, accent);
385 g.addColorStop(1, "#334155");
386 ctx.fillStyle = g;
387 ctx.fillRect(cx - r, cy - r, 2 * r, 2 * r);
388 ctx.fillStyle = "#0b1020";
389 ctx.font = "700 110px system-ui, sans-serif";
390 ctx.fillText(initials(userName), cx, cy + 6);
391 }
392 ctx.restore();
393 ctx.strokeStyle = accent;
394 ctx.lineWidth = 8;
395 ctx.beginPath();
396 ctx.arc(cx, cy, r + 8, 0, Math.PI * 2);
397 ctx.stroke();
398
399 // Name and role (shrunk to fit)
400 ctx.fillStyle = "#ffffff";
401 let size = 58;
402 do {
403 ctx.font = `700 ${size}px system-ui, sans-serif`;
404 size -= 2;
405 } while (ctx.measureText(userName).width > W - 80 && size > 24);
406 ctx.fillText(userName, W / 2, 548);
407 ctx.fillStyle = "rgba(255,255,255,0.6)";
408 ctx.font = "500 30px system-ui, sans-serif";
409 ctx.fillText(role, W / 2, 600);
410
411 // Access band
412 ctx.fillStyle = isVIP ? gold : "rgba(255,255,255,0.12)";
413 ctx.fillRect(0, 668, W, 70);
414 ctx.fillStyle = isVIP ? "#3b2a0a" : "rgba(255,255,255,0.85)";
415 ctx.font = "800 34px system-ui, sans-serif";
416 ctx.fillText(isVIP ? "V I P A C C E S S" : "S T A F F", W / 2, 704);
417
418 // Barcode (stable for a given name)
419 let seed = 0;
420 for (const c of userName) seed = (seed * 31 + c.charCodeAt(0)) >>> 0;
421 ctx.fillStyle = "rgba(255,255,255,0.8)";
422 let x = 60;
423 while (x < 330) {
424 seed = (seed * 1103515245 + 12345) >>> 0;
425 const w = 2 + (seed % 5);
426 ctx.fillRect(x, 790, w, 70);
427 x += w + 3 + ((seed >> 8) % 4);
428 }
429}
430
431/* -------------------------------------------------------------------------- */
432/* Hologram */
433/* -------------------------------------------------------------------------- */
434
435const holoVertex = /* glsl */ `
436varying vec2 vUv;
437varying vec3 vNormalW;
438varying vec3 vViewW;
439void main() {
440 vUv = uv;
441 vec4 world = modelMatrix * vec4(position, 1.0);
442 vNormalW = normalize(mat3(modelMatrix) * normal);
443 vViewW = normalize(cameraPosition - world.xyz);
444 gl_Position = projectionMatrix * viewMatrix * world;
445}
446`;
447
448// Thin-film rainbow that shifts with the viewing angle, over a fine guilloche pattern
449const holoFragment = /* glsl */ `
450uniform float uTime;
451varying vec2 vUv;
452varying vec3 vNormalW;
453varying vec3 vViewW;
454vec3 spectrum(float t) {
455 return 0.5 + 0.5 * cos(6.28318 * (t + vec3(0.0, 0.33, 0.67)));
456}
457void main() {
458 float facing = dot(normalize(vNormalW), normalize(vViewW));
459 float guilloche = sin((vUv.x * 9.0 + sin(vUv.y * 14.0) * 0.6) * 6.28318) * 0.5 + 0.5;
460 float t = facing * 2.4 + vUv.x * 0.8 + vUv.y * 0.5 + uTime * 0.05 + guilloche * 0.12;
461 vec3 color = spectrum(t);
462 float rim = smoothstep(0.0, 0.08, min(min(vUv.x, 1.0 - vUv.x), min(vUv.y, 1.0 - vUv.y)));
463 gl_FragColor = vec4(color, (0.55 + guilloche * 0.25) * rim);
464}
465`;
466
467/* -------------------------------------------------------------------------- */
468/* Scene */
469/* -------------------------------------------------------------------------- */
470
471function Badge({ userName, role, avatarUrl, badgeColor, isVIP }: Required<Omit<SecurityBadgeProps, "primaryColor" | "pauseWhenOffscreen" | "lowPowerMode" | "avatarUrl">> & { avatarUrl?: string }) {
472 const res = useDisposable(() => {
473 const canvas = document.createElement("canvas");
474 canvas.width = TEX.width;
475 canvas.height = TEX.height;
476 const face = new THREE.CanvasTexture(canvas);
477 face.colorSpace = THREE.SRGBColorSpace;
478 face.anisotropy = 8;
479 return {
480 face,
481 faceMaterial: new THREE.MeshPhysicalMaterial({ map: face, roughness: 0.4, clearcoat: 1, clearcoatRoughness: 0.12 }),
482 body: new THREE.MeshPhysicalMaterial({ roughness: 0.5 }),
483 faceGeometry: roundedPlane(CARD.width - 0.01, CARD.height - 0.01, 0.095),
484 edge: new THREE.MeshPhysicalMaterial({ roughness: 0.3, metalness: 1 }),
485 chip: new THREE.MeshStandardMaterial({ metalness: 0.65, roughness: 0.3, emissive: new THREE.Color(0, 0, 0) }),
486 strap: new THREE.MeshStandardMaterial({ roughness: 0.8 }),
487 steel: new THREE.MeshStandardMaterial({ color: "#d4d4d8", metalness: 1, roughness: 0.2 }),
488 holo: new THREE.ShaderMaterial({
489 uniforms: { uTime: { value: 0 } },
490 vertexShader: holoVertex,
491 fragmentShader: holoFragment,
492 transparent: true,
493 depthWrite: false,
494 }),
495 strapGeometry: new THREE.BoxGeometry(0.16, 1, 0.012),
496 holoGeometry: new THREE.PlaneGeometry(0.62, 0.42),
497 chipGeometry: new THREE.BoxGeometry(0.34, 0.26, 0.012),
498 clipGeometry: new THREE.TorusGeometry(0.1, 0.028, 10, 24),
499 };
500 }, []);
501 const canvas = res.face.image as HTMLCanvasElement;
502
503 // Redraw the face when the props change, and once more when the photo has loaded
504 useEffect(() => {
505 const ctx = canvas.getContext("2d")!;
506 const draw = (img: HTMLImageElement | null) => {
507 drawFace(ctx, { userName, role, badgeColor, isVIP }, img);
508 res.face.needsUpdate = true;
509 };
510 draw(null);
511 if (!avatarUrl) return undefined;
512 let cancelled = false;
513 const img = new Image();
514 img.crossOrigin = "anonymous";
515 img.onload = () => !cancelled && draw(img);
516 img.src = avatarUrl;
517 return () => {
518 cancelled = true;
519 };
520 }, [canvas, res, userName, role, avatarUrl, badgeColor, isVIP]);
521
522 useEffect(() => {
523 const metal = isVIP ? "#d9b26a" : "#c7ccd4";
524 res.edge.color.set(metal);
525 res.chip.color.set(isVIP ? "#e2bb6b" : "#b8bec8");
526 // A touch of self-light so the contact chip still reads on a dark card
527 res.chip.emissive.set(isVIP ? "#e2bb6b" : "#b8bec8").multiplyScalar(0.18);
528 res.strap.color.set(isVIP ? "#111827" : badgeColor);
529 res.body.color.set(badgeColor);
530 }, [res, isVIP, badgeColor]);
531
532 const swing = useRef<THREE.Group>(null);
533 const straps = useRef<(THREE.Mesh | null)[]>([]);
534 const physics = useRef({ angle: 0, velocity: 0, turn: 0, tilt: 0, pivotX: 0 });
535 const scratch = useMemo(() => ({ pivot: new THREE.Vector3(), anchor: new THREE.Vector3(), dir: new THREE.Vector3() }), []);
536
537 useFrame((state, delta) => {
538 const dt = Math.min(delta, 1 / 30);
539 const p = physics.current;
540 res.holo.uniforms.uTime.value = state.clock.elapsedTime;
541
542 // The neck moves a little with the pointer; the card swings behind it on a damped pendulum
543 const prevX = p.pivotX;
544 p.pivotX += (state.pointer.x * 0.35 - p.pivotX) * (1 - Math.exp(-4 * dt));
545 const push = (p.pivotX - prevX) / Math.max(dt, 1e-3);
546 p.velocity += (-p.angle * 14 - p.velocity * 2.4 + push * 1.6) * dt;
547 p.angle += p.velocity * dt;
548 // ...and turns and leans towards the pointer, so the hologram catches the light
549 p.turn += (state.pointer.x * 0.55 - p.turn) * (1 - Math.exp(-5 * dt));
550 p.tilt += (-state.pointer.y * 0.25 - p.tilt) * (1 - Math.exp(-5 * dt));
551
552 const g = swing.current;
553 if (g) {
554 g.position.set(PIVOT.x + p.pivotX, PIVOT.y, PIVOT.z);
555 g.rotation.set(p.tilt, p.turn, p.angle);
556 }
557
558 // Lanyard: two straps from the clip up to the neck, off the top of the frame
559 scratch.pivot.set(PIVOT.x + p.pivotX, PIVOT.y + 0.1, PIVOT.z - 0.02);
560 [-1, 1].forEach((side, i) => {
561 const strap = straps.current[i];
562 if (!strap) return;
563 scratch.anchor.set(side * 0.55 + p.pivotX * 0.3, PIVOT.y + 3.2, -0.25);
564 stretchBetween(strap, scratch.pivot, scratch.anchor, scratch.dir);
565 });
566 });
567
568 const front = CARD.depth / 2 + 0.001;
569 return (
570 <>
571 {[0, 1].map((i) => (
572 <mesh
573 key={i}
574 ref={(el) => {
575 straps.current[i] = el;
576 }}
577 geometry={res.strapGeometry}
578 material={res.strap}
579 />
580 ))}
581 <group ref={swing}>
582 <mesh geometry={res.clipGeometry} material={res.steel} position={[0, 0.02, 0]} />
583 <group position={[0, -CARD.height / 2 - 0.1, 0]}>
584 {/* Metal rim (gold for VIP), then the printed card on top */}
585 <RoundedBox args={[CARD.width + 0.05, CARD.height + 0.05, CARD.depth * 0.8]} radius={0.12} smoothness={4} material={res.edge} castShadow />
586 <RoundedBox args={[CARD.width, CARD.height, CARD.depth]} radius={0.1} smoothness={4} material={res.body} />
587 <mesh geometry={res.faceGeometry} material={res.faceMaterial} position={[0, 0, front]} />
588 <mesh geometry={res.chipGeometry} material={res.chip} position={[-0.8, 0.45, front + 0.006]} rotation={[0, 0, Math.PI / 2]} />
589 <mesh geometry={res.holoGeometry} material={res.holo} position={[0.55, -1.2, front + 0.002]} />
590 </group>
591 </group>
592 </>
593 );
594}
595
596/**
597 * Self-contained badge on a lanyard: fills its positioned parent. It swings with the pointer's
598 * movement and turns towards it; the security hologram shifts colours with the angle.
599 */
600function SecurityBadge3D({ userName, role, avatarUrl, primaryColor, badgeColor = primaryColor ?? "#0f172a", isVIP = false, pauseWhenOffscreen, lowPowerMode }: SecurityBadgeProps) {
601 return (
602 <ObjectCanvas pauseWhenOffscreen={pauseWhenOffscreen} lowPowerMode={lowPowerMode} camera={{ position: [0, 0.1, 7.4], fov: 34 }} dpr={[1, 2]}>
603 <ambientLight intensity={0.5} />
604 <directionalLight position={[3, 4, 5]} intensity={1.6} />
605 <StudioEnvironment intensity={0.9} />
606 <ResponsiveCamera minAspect={0.75} target={[0, 0, 0]} />
607 <Badge userName={userName} role={role} avatarUrl={avatarUrl} badgeColor={badgeColor} isVIP={isVIP} />
608 </ObjectCanvas>
609 );
610}
611
612export default memo(SecurityBadge3D);
03

Drop it in a page

Updated live with the settings above.

app/page.tsx
1import SecurityBadge3D from "@/components/SecurityBadge3D";
2
3export default function Section() {
4 return (
5 // The component fills this box: give it a position and a height
6 <div style={{ position: "relative", width: "100%", height: "100vh" }}>
7 <SecurityBadge3D
8 userName="Ada Lovelace"
9 role="Lead Engineer"
10 avatarUrl="/girl.jpg"
11 primaryColor="#0f172a"
12 isVIP
13 />
14 </div>
15 );
16}
Next componentInteractive Chart→