← All components Next componentGyroscopic Loader→
Extras · Card
Holographic Card
A trading-card slab with a holographic foil that shifts with the angle, layered in depth and tilting towards the cursor.
<HolographicCard3D />Live
Hover to tilt the card
Customize
Tilt axis
Card#121019
Installation
Use it in your project
Or skip the copy-paste
One command: writes the file and installs the dependencies.
$ npx deepui-cli add holographic-card
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/HolographicCard3D.tsx and paste it in.
components/HolographicCard3D.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 { Canvas, useFrame, useThree, type CanvasProps, type ThreeEvent } from "@react-three/fiber";18import { Environment, Lightformer, useTexture } from "@react-three/drei";1920/**21 * The shared props API of DeepUI's individual 3D components (not the full-page templates, which keep22 * their own tailored scenes).23 *24 * The props are grouped by concern. A component extends ONLY the groups it really applies, so its25 * type never advertises a knob that does nothing (a card has no particles, a background has no tilt):26 *27 * interface MyCardProps extends CursorProps, TiltProps, MaterialProps, PerformanceProps { … }28 *29 * `Base3DComponentProps` is every group at once, for tooling that handles any component. Same name,30 * same unit and same meaning everywhere; the default values live in DEFAULT_3D_PROPS. These files are31 * inlined into each component's single-file bundle (lib/bundle-source.mjs), only what it uses.32 */3334/** Which rotation axes follow the pointer. "x-only": the object nods (up / down); "y-only": it turns (left / right). */35export type TiltAxis = "both" | "x-only" | "y-only" | "none";3637/** 1. Cursor: how the pointer pulls, pushes and drags the object. */38interface CursorProps {39 /** 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). */40 cursorRadius?: number;41 /** Positive pulls things towards the pointer, negative pushes them away (repulsion, shockwave). Default 1. */42 cursorForce?: number;43 /** How far the object slides towards the pointer, 0 (stays put) to 1 (follows closely). Default 0. */44 magneticStrength?: number;45 /** Share of the remaining distance the motion closes each frame (at 60 fps), 0.01 (heavy, slow) to 1 (instant). Default 0.1. */46 cursorDamping?: number;47}4849/** 2. Tilt and parallax: the object leans towards the pointer, its layers slide against each other. */50interface TiltProps {51 /** Largest lean towards the pointer, in degrees. Default 15. */52 maxTiltAngle?: number;53 /** Axes that follow the pointer. Default "both". */54 tiltAxis?: TiltAxis;55 /** Lean away from the pointer instead of towards it. Default false. */56 invertTilt?: boolean;57 /** How far apart the depth layers slide when the object tilts, 0 (flat) to 2. Default 1. */58 parallaxOffset?: number;59}6061/** 3. Text and 3D typography, for components that draw a label. */62interface Text3DProps {63 /** The label drawn by the component. */64 text?: string;65 /** Scale of the lettering. Default 1. */66 fontSize?: number;67 /** Extrusion depth of 3D letters. Default 0.2. */68 textDepth?: number;69 /** Bevelled, light-catching edges on 3D letters. Default true. */70 bevelEnabled?: boolean;71 /** Custom font: a .woff / .ttf (flat text) or a typeface .json (extruded text). */72 fontUrl?: string;73}7475/** 4. Rendering, materials and glow. */76interface MaterialProps {77 /** Main color of the object. Default "#6366f1". */78 primaryColor?: string;79 /** Color of the glow. Default "#00f0ff". */80 emissiveColor?: string;81 /** Strength of the glow, 0 (none) to 3. Default 1. */82 emissiveIntensity?: number;83 /** 0 (mirror, glass) to 1 (matte). Default 0.3. */84 roughness?: number;85 /** 0 (plastic, organic) to 1 (metal). Default 0.5. */86 metalness?: number;87 /** 0 (opaque) to 1 (clear glass): see-through, refracting surfaces. Default 0. */88 transmission?: number;89 /** Technical wireframe rendering. Default false. */90 wireframe?: boolean;91}9293/** 5. Particles, idle motion and shader animation. */94interface MotionProps {95 /** Number of instanced elements. Default depends on the component. */96 particleCount?: number;97 /** Spin on its own, in radians per second (negative: the other way; 0.5 ≈ one turn in 12 s). Default 0. */98 autoRotateSpeed?: number;99 /** Pulses or ripples per second. Default 1. */100 pulseRate?: number;101 /** Amplitude of the noise deformation, 0 (none) to 2. Default 1. */102 displacementScale?: number;103}104105/** 6. Environment and camera. */106interface EnvironmentProps {107 /** Camera field of view, in degrees. Default depends on the component. */108 cameraFov?: number;109 /** Color of the depth fog. Default "#0a0a0a". */110 fogColor?: string;111 /** Thickness of the fog, 0 (none) to 0.2. Default 0. */112 fogDensity?: number;113}114115/** 7. Performance and accessibility. */116interface PerformanceProps {117 /** Lighter rendering for weak devices: pixel ratio 1, fewer instances, smaller environment maps. Default false. */118 lowPowerMode?: boolean;119 /** Under the OS "reduce motion" setting, stop idle spin, pulses and deformation (pointer feedback stays). Default true. */120 respectReducedMotion?: boolean;121 /** Stop the render loop while the component is scrolled out of view. Default true. */122 pauseWhenOffscreen?: boolean;123}124125/** Every group at once. Components extend only the groups they apply (see the top of this file). */126interface Base3DComponentProps127 extends CursorProps,128 TiltProps,129 Text3DProps,130 MaterialProps,131 MotionProps,132 EnvironmentProps,133 PerformanceProps {}134135type Defaults = Required<Omit<Base3DComponentProps, "text" | "fontUrl" | "particleCount" | "cameraFov">>;136137/** The values a prop takes when it is left out. A component may override one, and then documents it. */138const DEFAULT_3D_PROPS: Defaults = {139 cursorRadius: 220,140 cursorForce: 1,141 magneticStrength: 0,142 cursorDamping: 0.1,143 maxTiltAngle: 15,144 tiltAxis: "both",145 invertTilt: false,146 parallaxOffset: 1,147 fontSize: 1,148 textDepth: 0.2,149 bevelEnabled: true,150 primaryColor: "#6366f1",151 emissiveColor: "#00f0ff",152 emissiveIntensity: 1,153 roughness: 0.3,154 metalness: 0.5,155 transmission: 0,156 wireframe: false,157 autoRotateSpeed: 0,158 pulseRate: 1,159 displacementScale: 1,160 fogColor: "#0a0a0a",161 fogDensity: 0,162 lowPowerMode: false,163 respectReducedMotion: true,164 pauseWhenOffscreen: true,165};166167/** Inline widget: fills its positioned parent and receives pointer events. */168const FILL_STYLE: CSSProperties = { position: "absolute", top: 0, left: 0, width: "100%", height: "100%" };169170/** Cursor overlay: covers the viewport, above everything, never intercepts the page's events. */171const OVERLAY_STYLE: CSSProperties = {172 position: "fixed",173 top: 0,174 left: 0,175 width: "100%",176 height: "100%",177 pointerEvents: "none",178 zIndex: 9999,179};180181/** Visually hidden but reachable by keyboard and screen readers. */182const SR_ONLY: CSSProperties = {183 position: "absolute",184 width: 1,185 height: 1,186 padding: 0,187 margin: -1,188 overflow: "hidden",189 clip: "rect(0, 0, 0, 0)",190 whiteSpace: "nowrap",191 border: 0,192};193194interface UICanvasProps extends Omit<CanvasProps, "children" | "style" | "gl">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {195 children: ReactNode;196 /** Full-viewport, click-through overlay (cursors) instead of an inline widget. */197 overlay?: boolean;198}199200/**201 * Ready-to-use <Canvas>: pauses its render loop while scrolled out of view (pauseWhenOffscreen), pixel202 * ratio 1 in lowPowerMode; R3F disposes the renderer and its WebGL context on unmount.203 */204function UICanvas({ children, overlay = false, dpr = [1, 2], pauseWhenOffscreen = DEFAULT_3D_PROPS.pauseWhenOffscreen, lowPowerMode = DEFAULT_3D_PROPS.lowPowerMode, ...canvasProps }: UICanvasProps) {205 const containerRef = useRef<HTMLDivElement>(null);206 // In view at first: the first frame is always drawn before the loop can be paused207 const [inView, setInView] = useState(true);208 useEffect(() => {209 const el = containerRef.current;210 if (!el || !pauseWhenOffscreen) return undefined;211 const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting));212 observer.observe(el);213 return () => observer.disconnect();214 }, [pauseWhenOffscreen]);215 return (216 <div ref={containerRef} style={overlay ? OVERLAY_STYLE : FILL_STYLE} aria-hidden="true">217 <Canvas218 dpr={lowPowerMode ? 1 : dpr}219 frameloop={inView || !pauseWhenOffscreen ? "always" : "never"}220 gl={{ antialias: true, alpha: true, powerPreference: "high-performance" }}221 style={overlay ? { pointerEvents: "none" } : undefined}222 {...canvasProps}223 >224 {children}225 </Canvas>226 </div>227 );228}229230/**231 * Perspective camera placed so that 1 world unit = 1 CSS pixel on the z = 0 plane: widgets are laid232 * out in pixels like the rest of the page, and still get real depth (presses, tilts, shadows).233 */234function PixelPerspective({ fov = 30 }: { fov?: number }) {235 const camera = useThree((state) => state.camera) as THREE.PerspectiveCamera;236 const size = useThree((state) => state.size);237 useLayoutEffect(() => {238 camera.fov = fov;239 camera.near = 1;240 camera.far = 20000;241 camera.position.set(0, 0, size.height / 2 / Math.tan(THREE.MathUtils.degToRad(fov / 2)));242 camera.lookAt(0, 0, 0);243 camera.updateProjectionMatrix();244 }, [camera, size, fov]);245 return null;246}247248function pageFontFamily() {249 if (typeof document === "undefined") return "sans-serif";250 return getComputedStyle(document.body).fontFamily || "sans-serif";251}252253interface LabelOptions {254 text: string;255 /** Second, smaller line under the text. */256 subtext?: string;257 /** Glyph drawn before the text (emoji, arrow, symbol…). */258 icon?: string;259 width: number;260 height: number;261 color: string;262 /** Face color; transparent when omitted. */263 background?: string;264 fontSize?: number;265 fontWeight?: number;266 /** Wrap the text over several lines within the width (minus padding). */267 wrap?: boolean;268 align?: "center" | "left";269 /** Horizontal padding, in CSS pixels (used by wrapping and left alignment). Default 0. */270 padding?: number;271 /** Line height, as a multiple of the font size. Default 1.35. */272 lineHeight?: number;273}274275function wrapLines(ctx: CanvasRenderingContext2D, text: string, maxWidth: number) {276 const lines: string[] = [];277 let line = "";278 for (const word of text.split(/\s+/)) {279 const candidate = line ? `${line} ${word}` : word;280 if (line && ctx.measureText(candidate).width > maxWidth) {281 lines.push(line);282 line = word;283 } else {284 line = candidate;285 }286 }287 if (line) lines.push(line);288 return lines;289}290291function drawLabel(canvas: HTMLCanvasElement, o: LabelOptions) {292 // Drawn at 2× (or the screen's ratio) so the text stays crisp once mapped on its plane293 const scale = Math.min(Math.max(window.devicePixelRatio || 1, 2), 3);294 canvas.width = Math.max(2, Math.ceil(o.width * scale));295 canvas.height = Math.max(2, Math.ceil(o.height * scale));296 const ctx = canvas.getContext("2d");297 if (!ctx) return;298 ctx.setTransform(scale, 0, 0, scale, 0, 0);299 ctx.clearRect(0, 0, o.width, o.height);300 if (o.background) {301 ctx.fillStyle = o.background;302 ctx.fillRect(0, 0, o.width, o.height);303 }304305 const family = pageFontFamily();306 const size = o.fontSize ?? 15;307 const weight = o.fontWeight ?? 600;308 ctx.fillStyle = o.color;309 ctx.textBaseline = "middle";310 ctx.textAlign = "center";311312 const padding = o.padding ?? 0;313 const left = o.align === "left";314 ctx.textAlign = left ? "left" : "center";315 const x = left ? padding : o.width / 2;316317 let text = o.text;318 if (o.icon) text = `${o.icon} ${text}`;319 ctx.font = `${weight} ${size}px ${family}`;320321 if (o.wrap) {322 const step = size * (o.lineHeight ?? 1.35);323 const lines = wrapLines(ctx, text, o.width - padding * 2);324 // Only as many lines as fit; the last one kept ends with an ellipsis325 const maxLines = Math.max(1, Math.floor(o.height / step));326 if (lines.length > maxLines) {327 lines.length = maxLines;328 let last = lines[maxLines - 1];329 while (last && ctx.measureText(`${last}…`).width > o.width - padding * 2) last = last.slice(0, -1);330 lines[maxLines - 1] = `${last.trimEnd()}…`;331 }332 const top = o.height / 2 - ((lines.length - 1) * step) / 2;333 lines.forEach((line, i) => ctx.fillText(line, x, top + i * step));334 return;335 }336337 const mainY = o.subtext ? o.height * 0.4 : o.height / 2;338 ctx.fillText(text, x, mainY);339340 if (o.subtext) {341 ctx.globalAlpha = 0.7;342 ctx.font = `500 ${Math.round(size * 0.72)}px ${family}`;343 ctx.fillText(o.subtext, x, o.height * 0.7);344 ctx.globalAlpha = 1;345 }346}347348/**349 * Text drawn into a CanvasTexture, in the page's own font: no font file to download (unlike drei's350 * <Text>). Redrawn once web fonts finish loading; disposed on unmount.351 */352function useLabelTexture(options: LabelOptions) {353 const key = JSON.stringify(options);354 const [fontsVersion, setFontsVersion] = useState(0);355 useEffect(() => {356 let alive = true;357 document.fonts?.ready.then(() => {358 if (alive) setFontsVersion((v) => v + 1);359 });360 return () => {361 alive = false;362 };363 }, []);364365 const texture = useMemo(() => {366 const t = new THREE.CanvasTexture(document.createElement("canvas"));367 t.colorSpace = THREE.SRGBColorSpace;368 t.anisotropy = 4;369 return t;370 }, []);371372 useLayoutEffect(() => {373 drawLabel(texture.image as HTMLCanvasElement, JSON.parse(key) as LabelOptions);374 texture.needsUpdate = true;375 }, [texture, key, fontsVersion]);376377 useEffect(() => () => texture.dispose(), [texture]);378 return texture;379}380381/** Rounded-rectangle outline centered on the origin (radius clamped to a pill). */382function roundedRectShape(width: number, height: number, radius: number) {383 const r = Math.min(radius, width / 2, height / 2);384 const x = -width / 2;385 const y = -height / 2;386 const shape = new THREE.Shape();387 shape.moveTo(x + r, y);388 shape.lineTo(x + width - r, y);389 shape.quadraticCurveTo(x + width, y, x + width, y + r);390 shape.lineTo(x + width, y + height - r);391 shape.quadraticCurveTo(x + width, y + height, x + width - r, y + height);392 shape.lineTo(x + r, y + height);393 shape.quadraticCurveTo(x, y + height, x, y + height - r);394 shape.lineTo(x, y + r);395 shape.quadraticCurveTo(x, y, x + r, y);396 return shape;397}398399/** Bevelled, extruded rounded rectangle, centered on the origin (front face at +depth/2 + bevel). */400function createBevelledSlab(width: number, height: number, radius: number, depth: number, bevel: number) {401 const geometry = new THREE.ExtrudeGeometry(roundedRectShape(width - bevel * 2, height - bevel * 2, Math.max(0, radius - bevel)), {402 depth,403 bevelEnabled: true,404 bevelThickness: bevel,405 bevelSize: bevel,406 bevelSegments: 6,407 curveSegments: 24,408 });409 geometry.translate(0, 0, -depth / 2);410 return geometry;411}412413/**414 * The shared behaviour behind the props of ./types: pointer inertia, tilt, magnetic pull, idle spin,415 * the OS "reduce motion" setting and the off-screen pause. Inlined into each component's bundle.416 */417418/** True while the OS asks for reduced motion; follows the setting live. */419function usePrefersReducedMotion(): boolean {420 const [reduced, setReduced] = useState(false);421 useEffect(() => {422 const query = window.matchMedia("(prefers-reduced-motion: reduce)");423 const sync = () => setReduced(query.matches);424 sync();425 query.addEventListener("change", sync);426 return () => query.removeEventListener("change", sync);427 }, []);428 return reduced;429}430431/**432 * `cursorDamping` (share of the gap closed per 60 fps frame) as a rate for THREE.MathUtils.damp, so the433 * motion feels the same at 30, 60 or 120 fps.434 */435function dampingToLambda(damping: number): number {436 const share = THREE.MathUtils.clamp(damping, 0.001, 0.999);437 return -Math.log(1 - share) * 60;438}439440interface ResolvedMotion {441 autoRotateSpeed: number;442 pulseRate: number;443 displacementScale: number;444}445446/** Idle motion after `respectReducedMotion`: under "reduce motion", no spin, no pulse, no deformation. */447function resolveMotion(props: MotionProps & PerformanceProps, reduced: boolean): ResolvedMotion {448 const still = reduced && (props.respectReducedMotion ?? DEFAULT_3D_PROPS.respectReducedMotion);449 return {450 autoRotateSpeed: still ? 0 : (props.autoRotateSpeed ?? DEFAULT_3D_PROPS.autoRotateSpeed),451 pulseRate: still ? 0 : (props.pulseRate ?? DEFAULT_3D_PROPS.pulseRate),452 displacementScale: still ? 0 : (props.displacementScale ?? DEFAULT_3D_PROPS.displacementScale),453 };454}455456/** A pointer position in -1…1 (x right, y up) and whether it is on the object. */457interface PointerSample {458 x: number;459 y: number;460 active: boolean;461}462463interface Interactive3DOptions extends CursorProps, TiltProps, MotionProps, PerformanceProps {464 /**465 * Where the pointer is. Default: over the whole canvas, active while the pointer is on it. Pass your466 * own ref to follow something else, e.g. the pointer in an object's local space while it is hovered.467 */468 pointer?: RefObject<PointerSample>;469 /** World units the object slides at magneticStrength 1. Default 0.5. */470 magneticDistance?: number;471 /** Where the "pointer" rests while inactive, from the elapsed seconds: an idle sway. Default: the center. */472 idle?: (time: number) => { x: number; y: number };473}474475/** Read each frame by the component, e.g. for shader uniforms. */476interface Interactive3DState {477 /** Smoothed pointer, -1…1. */478 x: number;479 y: number;480 /** Smoothed "pointer on it", 0…1: hover glows, lifts. */481 hover: number;482 /** The tilt applied this frame, in radians (x: nod, y: turn). */483 tiltX: number;484 tiltY: number;485 /** Idle motion after the reduce-motion setting. */486 motion: ResolvedMotion;487}488489/**490 * Drives `target` (a group, usually the whole object) from the shared props: it leans towards the491 * pointer within `maxTiltAngle` on the axes of `tiltAxis`, slides towards it with `magneticStrength`,492 * spins on its own at `autoRotateSpeed`; every motion eased by `cursorDamping`, frame-rate independent.493 * Call it inside the <Canvas> (it uses useFrame), before the component's own useFrame so the latter494 * reads this frame's values. Owns target.rotation.x/y and, when magnetic, target.position.x/y.495 */496function useInteractive3DControls(target: RefObject<THREE.Object3D | null>, options: Interactive3DOptions = {}): RefObject<Interactive3DState> {497 const {498 magneticStrength = DEFAULT_3D_PROPS.magneticStrength,499 cursorDamping = DEFAULT_3D_PROPS.cursorDamping,500 maxTiltAngle = DEFAULT_3D_PROPS.maxTiltAngle,501 tiltAxis = DEFAULT_3D_PROPS.tiltAxis,502 invertTilt = DEFAULT_3D_PROPS.invertTilt,503 magneticDistance = 0.5,504 pointer,505 idle,506 } = options;507 const reduced = usePrefersReducedMotion();508 const motion = resolveMotion(options, reduced);509 const still = reduced && (options.respectReducedMotion ?? DEFAULT_3D_PROPS.respectReducedMotion);510511 const canvasPointer = useThree((state) => state.pointer);512 const gl = useThree((state) => state.gl);513 const over = useRef(false);514 useEffect(() => {515 if (pointer) return undefined;516 const el = gl.domElement;517 const enter = () => (over.current = true);518 const leave = () => (over.current = false);519 el.addEventListener("pointerenter", enter);520 el.addEventListener("pointerleave", leave);521 return () => {522 el.removeEventListener("pointerenter", enter);523 el.removeEventListener("pointerleave", leave);524 };525 }, [gl, pointer]);526527 const state = useRef<Interactive3DState>({ x: 0, y: 0, hover: 0, tiltX: 0, tiltY: 0, motion });528 const spin = useRef(0);529 const base = useRef<THREE.Vector2 | null>(null);530531 useFrame((frame, delta) => {532 const object = target.current;533 const s = state.current;534 s.motion = motion;535 if (!object) return;536 const dt = Math.min(delta, 1 / 20);537 const lambda = dampingToLambda(cursorDamping);538539 const source = pointer?.current ?? { x: canvasPointer.x, y: canvasPointer.y, active: over.current };540 const rest = idle && !still ? idle(frame.clock.elapsedTime) : { x: 0, y: 0 };541 const goalX = source.active ? THREE.MathUtils.clamp(source.x, -1, 1) : rest.x;542 const goalY = source.active ? THREE.MathUtils.clamp(source.y, -1, 1) : rest.y;543 s.x = THREE.MathUtils.damp(s.x, goalX, lambda, dt);544 s.y = THREE.MathUtils.damp(s.y, goalY, lambda, dt);545 s.hover = THREE.MathUtils.damp(s.hover, source.active ? 1 : 0, lambda * 0.8, dt);546547 // Tilt: pointer up → the top leans back (negative x); pointer right → the face turns right (positive y)548 const max = THREE.MathUtils.degToRad(maxTiltAngle) * (invertTilt ? -1 : 1);549 s.tiltX = tiltAxis === "both" || tiltAxis === "x-only" ? -s.y * max : 0;550 s.tiltY = tiltAxis === "both" || tiltAxis === "y-only" ? s.x * max : 0;551552 spin.current += motion.autoRotateSpeed * dt;553 object.rotation.x = s.tiltX;554 object.rotation.y = spin.current + s.tiltY;555556 if (magneticStrength > 0) {557 if (!base.current) base.current = new THREE.Vector2(object.position.x, object.position.y);558 object.position.x = base.current.x + s.x * s.hover * magneticStrength * magneticDistance;559 object.position.y = base.current.y + s.y * s.hover * magneticStrength * magneticDistance;560 }561 });562563 return state;564}565566/**567 * The shared 3D props (../core/types) this card applies. Its own defaults: maxTiltAngle 18,568 * primaryColor "#121019" (the slab), emissiveIntensity 0.8 (the holographic foil).569 */570export interface HolographicCardProps571 extends Pick<CursorProps, "magneticStrength" | "cursorDamping">,572 TiltProps,573 Pick<MaterialProps, "primaryColor" | "emissiveIntensity" | "roughness" | "metalness" | "wireframe">,574 Pick<MotionProps, "autoRotateSpeed">,575 PerformanceProps {576 title: string;577 description?: string;578 /** Image shown in the card's window (cover-fitted). A violet gradient is drawn when omitted. */579 image?: string;580 /** @deprecated Use maxTiltAngle (degrees). Maximum tilt in radians. */581 tiltAmount?: number;582 /** @deprecated Use emissiveIntensity. Strength of the holographic foil. */583 iridescentIntensity?: number;584}585586const RATIO = 1.42; // height / width, like a trading card587const MAX_WIDTH = 300;588const RADIUS = 20;589const DEPTH = 8;590const BEVEL = 3;591const INSET = 14;592const FRONT = DEPTH / 2 + BEVEL; // z of the card's face593// Inner layers sit at different depths: when the card tilts they slide against each other (parallax).594// Gaps above the face, scaled by parallaxOffset.595const IMAGE_GAP = 6;596const TEXT_GAP = 14;597const FOIL_GAP = 18;598599const planeVertex = /* glsl */ `600varying vec2 vUv;601void main() {602 vUv = uv;603 gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);604}605`;606607const ROUNDED_MASK = /* glsl */ `608float roundedMask(vec2 uv, vec2 size, float radius) {609 vec2 p = (uv - 0.5) * size;610 vec2 q = abs(p) - (size * 0.5 - radius);611 float d = length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - radius;612 float aa = fwidth(d);613 return 1.0 - smoothstep(-aa, aa, d);614}615`;616617// Image window: cover-fit, rounded, shifted against the tilt for depth; a gradient when there is no image618const windowFragment = /* glsl */ `619uniform sampler2D uMap;620uniform float uHasMap;621uniform float uImageAspect;622uniform vec2 uSize;623uniform vec2 uShift;624varying vec2 vUv;625${ROUNDED_MASK}626void main() {627 float mask = roundedMask(vUv, uSize, 12.0);628 if (mask < 0.01) discard;629 vec3 color;630 if (uHasMap > 0.5) {631 float planeAspect = uSize.x / uSize.y;632 vec2 scale = planeAspect > uImageAspect ? vec2(1.0, uImageAspect / planeAspect) : vec2(planeAspect / uImageAspect, 1.0);633 vec2 uv = (vUv - 0.5) * scale / 1.12 + 0.5 + uShift;634 color = texture2D(uMap, uv).rgb;635 } else {636 float g = vUv.y + uShift.y * 4.0;637 color = mix(vec3(0.05, 0.03, 0.12), vec3(0.55, 0.36, 0.98), smoothstep(0.0, 1.2, g));638 float grid = max(step(0.97, fract((vUv.x + uShift.x) * 12.0)), step(0.97, fract(vUv.y * 9.0)));639 color += grid * 0.06;640 }641 gl_FragColor = vec4(color, mask);642 #include <colorspace_fragment>643}644`;645646// Holographic foil: angle-dependent rainbow bands, fine diffraction lines, sparkles and a glare that647// follows the pointer. Additive, over the whole card.648const foilFragment = /* glsl */ `649uniform vec2 uSize;650uniform vec2 uPointer; // 0..1 across the card651uniform vec2 uTilt; // current tilt (radians)652uniform float uTime;653uniform float uIntensity;654uniform float uHover;655varying vec2 vUv;656${ROUNDED_MASK}657658float hash(vec2 p) {659 return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453);660}661662void main() {663 float mask = roundedMask(vUv, uSize, ${RADIUS.toFixed(1)});664 if (mask < 0.01) discard;665666 // The band pattern moves with the viewing angle: tilting the card sweeps the colors across it667 float angle = uTilt.y * 3.2 - uTilt.x * 2.4;668 float band = (vUv.x * 0.9 + vUv.y * 1.3) * 2.2 + angle + uTime * 0.03;669 vec3 holo = 0.5 + 0.5 * cos(6.2831 * (band + vec3(0.0, 0.33, 0.67)));670 holo = mix(holo, vec3(0.78, 0.7, 1.0), 0.35); // keep it pastel, leaning violet671672 float lines = 0.5 + 0.5 * sin((vUv.x - vUv.y) * 220.0);673 vec2 cell = floor(vUv * vec2(70.0, 100.0));674 float sparkle = step(0.988, hash(cell)) * pow(0.5 + 0.5 * sin(uTime * 3.0 + hash(cell + 7.0) * 6.2831 + angle * 6.0), 6.0);675676 float glare = exp(-distance(vUv, uPointer) * 3.5);677 // Full foil over the image, lighter over the text so it stays readable678 float strength = uIntensity * (0.3 + 0.7 * uHover) * mix(0.35, 1.0, smoothstep(0.38, 0.5, vUv.y));679680 vec3 color = holo * strength * (0.22 + 0.16 * lines) + vec3(1.0) * glare * 0.32 * uHover + sparkle * strength * 0.9;681 gl_FragColor = vec4(color * mask, 1.0);682 #include <colorspace_fragment>683}684`;685686class ImageErrorBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {687 state = { failed: false };688 static getDerivedStateFromError() {689 return { failed: true };690 }691 render() {692 return this.state.failed ? null : this.props.children;693 }694}695696/** Loads the image as a texture (suspends) and hands it to the window material. */697function WindowImage({ url, material }: { url: string; material: THREE.ShaderMaterial }) {698 const texture = useTexture(url);699 useLayoutEffect(() => {700 texture.colorSpace = THREE.SRGBColorSpace;701 texture.needsUpdate = true;702 const image = texture.image as { width?: number; height?: number } | undefined;703 material.uniforms.uMap.value = texture;704 material.uniforms.uImageAspect.value = image?.width && image?.height ? image.width / image.height : 1;705 material.uniforms.uHasMap.value = 1;706 return () => {707 material.uniforms.uHasMap.value = 0;708 };709 }, [texture, material]);710 useEffect(() => () => texture.dispose(), [texture]);711 return null;712}713714const Card = memo(function Card({715 title,716 description,717 image,718 tiltAmount,719 iridescentIntensity,720 maxTiltAngle = tiltAmount !== undefined ? THREE.MathUtils.radToDeg(tiltAmount) : 18,721 tiltAxis,722 invertTilt,723 parallaxOffset = DEFAULT_3D_PROPS.parallaxOffset,724 magneticStrength,725 cursorDamping,726 autoRotateSpeed,727 respectReducedMotion,728 primaryColor = "#121019",729 emissiveIntensity = iridescentIntensity ?? 0.8,730 roughness = DEFAULT_3D_PROPS.roughness,731 metalness = DEFAULT_3D_PROPS.metalness,732 wireframe = DEFAULT_3D_PROPS.wireframe,733}: HolographicCardProps) {734 const size = useThree((state) => state.size);735 const gl = useThree((state) => state.gl);736 const groupRef = useRef<THREE.Group>(null);737 // The pointer in the card's own space, while it is hovered738 const pointer = useRef<PointerSample>({ x: 0, y: 0, active: false });739 const controls = useInteractive3DControls(groupRef, {740 pointer,741 maxTiltAngle,742 tiltAxis,743 invertTilt,744 magneticStrength,745 cursorDamping,746 autoRotateSpeed,747 respectReducedMotion,748 magneticDistance: 40,749 // At rest, a slow sway so the foil keeps catching the light750 idle: (t) => ({ x: Math.sin(t * 0.45) * 0.18, y: -Math.sin(t * 0.6) * 0.12 }),751 });752 const imageZ = FRONT + IMAGE_GAP * parallaxOffset;753 const textZ = FRONT + TEXT_GAP * parallaxOffset;754 const foilZ = FRONT + FOIL_GAP * parallaxOffset;755756 // Card size from the container, at most MAX_WIDTH wide, trading-card proportions757 let width = Math.min(size.width - 48, MAX_WIDTH);758 let height = width * RATIO;759 if (height > size.height - 48) {760 height = size.height - 48;761 width = height / RATIO;762 }763 width = Math.max(120, Math.round(width));764 height = Math.max(170, Math.round(height));765 const windowW = width - INSET * 2;766 const windowH = Math.round(windowW * 0.78);767 const windowY = height / 2 - INSET - windowH / 2;768 const textH = height - INSET * 3 - windowH;769 const textY = -height / 2 + INSET + textH / 2;770771 // Text scales with the card, so a small card keeps the same layout instead of overflowing772 const fontScale = Math.min(1, width / MAX_WIDTH);773 const titleH = Math.round(34 * fontScale);774 const titleTexture = useLabelTexture({ text: title, width: windowW, height: titleH, color: "#ffffff", fontSize: Math.max(11, 19 * fontScale), fontWeight: 700, align: "left" });775 const descriptionH = Math.max(16, textH - titleH - 6);776 const descriptionTexture = useLabelTexture({777 text: description ?? "",778 width: windowW,779 height: descriptionH,780 color: "#a1a1aa",781 fontSize: Math.max(9, 12.5 * fontScale),782 fontWeight: 500,783 align: "left",784 wrap: true,785 });786787 const slabGeometry = useMemo(() => createBevelledSlab(width, height, RADIUS, DEPTH, BEVEL), [width, height]);788 const plane = useMemo(() => new THREE.PlaneGeometry(1, 1), []);789 const slabMaterial = useMemo(() => new THREE.MeshPhysicalMaterial({ clearcoat: 1, clearcoatRoughness: 0.15 }), []);790 useEffect(() => {791 slabMaterial.color.set(primaryColor);792 slabMaterial.roughness = roughness;793 slabMaterial.metalness = metalness;794 slabMaterial.wireframe = wireframe;795 }, [slabMaterial, primaryColor, roughness, metalness, wireframe]);796 const windowMaterial = useMemo(797 () =>798 new THREE.ShaderMaterial({799 uniforms: {800 uMap: { value: null },801 uHasMap: { value: 0 },802 uImageAspect: { value: 1 },803 uSize: { value: new THREE.Vector2(1, 1) },804 uShift: { value: new THREE.Vector2() },805 },806 vertexShader: planeVertex,807 fragmentShader: windowFragment,808 transparent: true,809 }),810 []811 );812 const foilMaterial = useMemo(813 () =>814 new THREE.ShaderMaterial({815 uniforms: {816 uSize: { value: new THREE.Vector2(1, 1) },817 uPointer: { value: new THREE.Vector2(0.5, 0.5) },818 uTilt: { value: new THREE.Vector2() },819 uTime: { value: 0 },820 uIntensity: { value: 0.8 },821 uHover: { value: 0 },822 },823 vertexShader: planeVertex,824 fragmentShader: foilFragment,825 transparent: true,826 depthWrite: false,827 blending: THREE.AdditiveBlending,828 }),829 []830 );831 const titleMaterial = useMemo(() => new THREE.MeshBasicMaterial({ transparent: true, depthWrite: false, toneMapped: false }), []);832 const descriptionMaterial = useMemo(() => new THREE.MeshBasicMaterial({ transparent: true, depthWrite: false, toneMapped: false }), []);833834 useEffect(() => {835 titleMaterial.map = titleTexture;836 titleMaterial.needsUpdate = true;837 descriptionMaterial.map = descriptionTexture;838 descriptionMaterial.needsUpdate = true;839 }, [titleMaterial, descriptionMaterial, titleTexture, descriptionTexture]);840 useEffect(() => {841 (windowMaterial.uniforms.uSize.value as THREE.Vector2).set(windowW, windowH);842 (foilMaterial.uniforms.uSize.value as THREE.Vector2).set(width, height);843 foilMaterial.uniforms.uIntensity.value = emissiveIntensity;844 }, [windowMaterial, foilMaterial, windowW, windowH, width, height, emissiveIntensity]);845 useEffect(() => () => slabGeometry.dispose(), [slabGeometry]);846 useEffect(847 () => () => {848 plane.dispose();849 [slabMaterial, windowMaterial, foilMaterial, titleMaterial, descriptionMaterial].forEach((m) => m.dispose());850 },851 [plane, slabMaterial, windowMaterial, foilMaterial, titleMaterial, descriptionMaterial]852 );853854 // Tilt, magnetic pull and idle sway come from useInteractive3DControls (called above, so it runs first)855 useFrame((frame) => {856 const group = groupRef.current;857 if (!group) return;858 const c = controls.current;859 group.position.z = c.hover * 24;860861 const fu = foilMaterial.uniforms;862 fu.uTime.value = frame.clock.elapsedTime;863 fu.uHover.value = c.hover;864 (fu.uTilt.value as THREE.Vector2).set(c.tiltX, c.tiltY);865 (fu.uPointer.value as THREE.Vector2).set(c.x * 0.5 + 0.5, c.y * 0.5 + 0.5);866 // The image slides a little against the tilt: it reads as set deeper than the frame867 (windowMaterial.uniforms.uShift.value as THREE.Vector2).set(-c.tiltY * 0.08 * parallaxOffset, c.tiltX * 0.08 * parallaxOffset);868 });869870 const onMove = (e: ThreeEvent<PointerEvent>) => {871 if (!groupRef.current) return;872 const local = groupRef.current.worldToLocal(e.point.clone());873 pointer.current.x = THREE.MathUtils.clamp(local.x / (width / 2), -1, 1);874 pointer.current.y = THREE.MathUtils.clamp(local.y / (height / 2), -1, 1);875 };876877 return (878 <group ref={groupRef}>879 <mesh880 geometry={slabGeometry}881 material={slabMaterial}882 onPointerOver={() => {883 pointer.current.active = true;884 gl.domElement.style.cursor = "pointer";885 }}886 onPointerOut={() => {887 pointer.current.active = false;888 gl.domElement.style.cursor = "";889 }}890 onPointerMove={onMove}891 />892 <mesh geometry={plane} material={windowMaterial} position={[0, windowY, imageZ]} scale={[windowW, windowH, 1]}>893 {image ? (894 <ImageErrorBoundary key={image}>895 <Suspense fallback={null}>896 <WindowImage url={image} material={windowMaterial} />897 </Suspense>898 </ImageErrorBoundary>899 ) : null}900 </mesh>901 <mesh geometry={plane} material={titleMaterial} position={[0, textY + textH / 2 - titleH / 2, textZ]} scale={[windowW, titleH, 1]} />902 {description ? (903 <mesh904 geometry={plane}905 material={descriptionMaterial}906 position={[0, textY + textH / 2 - titleH - 6 - descriptionH / 2, textZ]}907 scale={[windowW, descriptionH, 1]}908 />909 ) : null}910 <mesh geometry={plane} material={foilMaterial} position={[0, 0, foilZ]} scale={[width, height, 1]} />911 </group>912 );913});914915/** Self-contained card: fills its positioned parent and centers the card (up to 300px wide). */916function HolographicCard3D(props: HolographicCardProps) {917 const { lowPowerMode = DEFAULT_3D_PROPS.lowPowerMode, pauseWhenOffscreen } = props;918 return (919 <>920 <UICanvas pauseWhenOffscreen={pauseWhenOffscreen} lowPowerMode={lowPowerMode}>921 <PixelPerspective />922 <ambientLight intensity={0.5} />923 <directionalLight position={[-200, 300, 500]} intensity={1.6} />924 <Environment resolution={lowPowerMode ? 64 : 128} frames={1}>925 <Lightformer form="rect" intensity={2.5} position={[0, 5, 3]} rotation-x={Math.PI / 2} scale={[10, 2, 1]} />926 <Lightformer form="rect" intensity={1.5} position={[-5, 0, 3]} rotation-y={Math.PI / 2} scale={[2, 6, 1]} />927 </Environment>928 <Card {...props} />929 </UICanvas>930 <div style={SR_ONLY}>931 <h3>{props.title}</h3>932 {props.description ? <p>{props.description}</p> : null}933 </div>934 </>935 );936}937938export default memo(HolographicCard3D);
03
Drop it in a page
Updated live with the settings above.
app/page.tsx
1import HolographicCard3D from "@/components/HolographicCard3D";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 <HolographicCard3D8 title="Deep Interfaces"9 description="Copy-paste 3D scenes for landing pages. Tune them live, ship them today."10 image="/heart.jpg"11 tiltAxis="both"12 maxTiltAngle={18}13 magneticStrength={0}14 cursorDamping={0.1}15 parallaxOffset={1}16 emissiveIntensity={0.8}17 primaryColor="#121019"18 invertTilt={false}19 />20 </div>21 );22}