Loading…
← All components

Background · Glass

Glassmorphism

A glass knot and spheres refracting colored bands, with tunable transmission and chromatic aberration.

<GlassmorphismBackground />Live

Customize

Glass tint#ffffff

Installation

Use it in your project

Or skip the copy-paste

One command: writes the file and installs the dependencies.

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

components/GlassmorphismBackground.tsx
1"use client";
2
3import { memo, useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react";
4import * as THREE from "three";
5import { Canvas, useFrame, type CanvasProps } from "@react-three/fiber";
6import { Environment, Lightformer, MeshTransmissionMaterial } from "@react-three/drei";
7
8/**
9 * The shared props API of DeepUI's individual 3D components (not the full-page templates, which keep
10 * their own tailored scenes).
11 *
12 * The props are grouped by concern. A component extends ONLY the groups it really applies, so its
13 * type never advertises a knob that does nothing (a card has no particles, a background has no tilt):
14 *
15 * interface MyCardProps extends CursorProps, TiltProps, MaterialProps, PerformanceProps { … }
16 *
17 * `Base3DComponentProps` is every group at once, for tooling that handles any component. Same name,
18 * same unit and same meaning everywhere; the default values live in DEFAULT_3D_PROPS. These files are
19 * inlined into each component's single-file bundle (lib/bundle-source.mjs), only what it uses.
20 */
21
22/** Which rotation axes follow the pointer. "x-only": the object nods (up / down); "y-only": it turns (left / right). */
23export type TiltAxis = "both" | "x-only" | "y-only" | "none";
24
25/** 1. Cursor: how the pointer pulls, pushes and drags the object. */
26interface CursorProps {
27 /** 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). */
28 cursorRadius?: number;
29 /** Positive pulls things towards the pointer, negative pushes them away (repulsion, shockwave). Default 1. */
30 cursorForce?: number;
31 /** How far the object slides towards the pointer, 0 (stays put) to 1 (follows closely). Default 0. */
32 magneticStrength?: number;
33 /** Share of the remaining distance the motion closes each frame (at 60 fps), 0.01 (heavy, slow) to 1 (instant). Default 0.1. */
34 cursorDamping?: number;
35}
36
37/** 2. Tilt and parallax: the object leans towards the pointer, its layers slide against each other. */
38interface TiltProps {
39 /** Largest lean towards the pointer, in degrees. Default 15. */
40 maxTiltAngle?: number;
41 /** Axes that follow the pointer. Default "both". */
42 tiltAxis?: TiltAxis;
43 /** Lean away from the pointer instead of towards it. Default false. */
44 invertTilt?: boolean;
45 /** How far apart the depth layers slide when the object tilts, 0 (flat) to 2. Default 1. */
46 parallaxOffset?: number;
47}
48
49/** 3. Text and 3D typography, for components that draw a label. */
50interface Text3DProps {
51 /** The label drawn by the component. */
52 text?: string;
53 /** Scale of the lettering. Default 1. */
54 fontSize?: number;
55 /** Extrusion depth of 3D letters. Default 0.2. */
56 textDepth?: number;
57 /** Bevelled, light-catching edges on 3D letters. Default true. */
58 bevelEnabled?: boolean;
59 /** Custom font: a .woff / .ttf (flat text) or a typeface .json (extruded text). */
60 fontUrl?: string;
61}
62
63/** 4. Rendering, materials and glow. */
64interface MaterialProps {
65 /** Main color of the object. Default "#6366f1". */
66 primaryColor?: string;
67 /** Color of the glow. Default "#00f0ff". */
68 emissiveColor?: string;
69 /** Strength of the glow, 0 (none) to 3. Default 1. */
70 emissiveIntensity?: number;
71 /** 0 (mirror, glass) to 1 (matte). Default 0.3. */
72 roughness?: number;
73 /** 0 (plastic, organic) to 1 (metal). Default 0.5. */
74 metalness?: number;
75 /** 0 (opaque) to 1 (clear glass): see-through, refracting surfaces. Default 0. */
76 transmission?: number;
77 /** Technical wireframe rendering. Default false. */
78 wireframe?: boolean;
79}
80
81/** 5. Particles, idle motion and shader animation. */
82interface MotionProps {
83 /** Number of instanced elements. Default depends on the component. */
84 particleCount?: number;
85 /** Spin on its own, in radians per second (negative: the other way; 0.5 ≈ one turn in 12 s). Default 0. */
86 autoRotateSpeed?: number;
87 /** Pulses or ripples per second. Default 1. */
88 pulseRate?: number;
89 /** Amplitude of the noise deformation, 0 (none) to 2. Default 1. */
90 displacementScale?: number;
91}
92
93/** 6. Environment and camera. */
94interface EnvironmentProps {
95 /** Camera field of view, in degrees. Default depends on the component. */
96 cameraFov?: number;
97 /** Color of the depth fog. Default "#0a0a0a". */
98 fogColor?: string;
99 /** Thickness of the fog, 0 (none) to 0.2. Default 0. */
100 fogDensity?: number;
101}
102
103/** 7. Performance and accessibility. */
104interface PerformanceProps {
105 /** Lighter rendering for weak devices: pixel ratio 1, fewer instances, smaller environment maps. Default false. */
106 lowPowerMode?: boolean;
107 /** Under the OS "reduce motion" setting, stop idle spin, pulses and deformation (pointer feedback stays). Default true. */
108 respectReducedMotion?: boolean;
109 /** Stop the render loop while the component is scrolled out of view. Default true. */
110 pauseWhenOffscreen?: boolean;
111}
112
113/** Every group at once. Components extend only the groups they apply (see the top of this file). */
114interface Base3DComponentProps
115 extends CursorProps,
116 TiltProps,
117 Text3DProps,
118 MaterialProps,
119 MotionProps,
120 EnvironmentProps,
121 PerformanceProps {}
122
123type Defaults = Required<Omit<Base3DComponentProps, "text" | "fontUrl" | "particleCount" | "cameraFov">>;
124
125/** The values a prop takes when it is left out. A component may override one, and then documents it. */
126const DEFAULT_3D_PROPS: Defaults = {
127 cursorRadius: 220,
128 cursorForce: 1,
129 magneticStrength: 0,
130 cursorDamping: 0.1,
131 maxTiltAngle: 15,
132 tiltAxis: "both",
133 invertTilt: false,
134 parallaxOffset: 1,
135 fontSize: 1,
136 textDepth: 0.2,
137 bevelEnabled: true,
138 primaryColor: "#6366f1",
139 emissiveColor: "#00f0ff",
140 emissiveIntensity: 1,
141 roughness: 0.3,
142 metalness: 0.5,
143 transmission: 0,
144 wireframe: false,
145 autoRotateSpeed: 0,
146 pulseRate: 1,
147 displacementScale: 1,
148 fogColor: "#0a0a0a",
149 fogDensity: 0,
150 lowPowerMode: false,
151 respectReducedMotion: true,
152 pauseWhenOffscreen: true,
153};
154
155/** Fills the positioned parent; never intercepts clicks meant for the page content above it. */
156const FILL_STYLE: CSSProperties = {
157 position: "absolute",
158 top: 0,
159 left: 0,
160 width: "100%",
161 height: "100%",
162 pointerEvents: "none",
163};
164
165interface BackgroundCanvasProps extends Omit<CanvasProps, "children" | "style" | "frameloop" | "gl">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {
166 children: ReactNode;
167}
168
169/**
170 * Ready-to-use <Canvas> shared by every background.
171 * - Pauses the render loop while the canvas is scrolled out of view.
172 * - Renders a single still frame when the user prefers reduced motion.
173 * - Caps the pixel ratio; R3F disposes the renderer and releases the WebGL
174 * context (forceContextLoss) when the Canvas unmounts.
175 */
176function BackgroundCanvas({ children, dpr = [1, 1.75], pauseWhenOffscreen = DEFAULT_3D_PROPS.pauseWhenOffscreen, lowPowerMode = DEFAULT_3D_PROPS.lowPowerMode, ...canvasProps }: BackgroundCanvasProps) {
177 const containerRef = useRef<HTMLDivElement>(null);
178 // Starts "in view" so the first frame is always drawn before the loop can be paused
179 const [inView, setInView] = useState(true);
180 const [reducedMotion, setReducedMotion] = useState(false);
181
182 useEffect(() => {
183 const el = containerRef.current;
184 if (!el) return undefined;
185 const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting));
186 observer.observe(el);
187
188 const query = window.matchMedia("(prefers-reduced-motion: reduce)");
189 const sync = () => setReducedMotion(query.matches);
190 sync();
191 query.addEventListener("change", sync);
192
193 return () => {
194 observer.disconnect();
195 query.removeEventListener("change", sync);
196 };
197 }, []);
198
199 return (
200 <div ref={containerRef} style={FILL_STYLE} aria-hidden="true">
201 <Canvas
202 dpr={lowPowerMode ? 1 : dpr}
203 frameloop={!inView && pauseWhenOffscreen ? "never" : reducedMotion ? "demand" : "always"}
204 gl={{ antialias: true, alpha: true, powerPreference: "high-performance" }}
205 style={{ pointerEvents: "none" }}
206 {...canvasProps}
207 >
208 {children}
209 </Canvas>
210 </div>
211 );
212}
213
214export interface GlassmorphismProps extends Pick<MaterialProps, "primaryColor" | "transmission" | "roughness">, Pick<MotionProps, "autoRotateSpeed">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {
215 /** 0–1. Default 0.95. */
216 transmission?: number;
217 /** Frosting of the glass. Default 0.15. */
218 roughness?: number;
219 /** Index of refraction. Default 1.2. */
220 ior?: number;
221 /** RGB split at the edges. Default 0.04. */
222 chromaticAberration?: number;
223 /** Refraction depth. Default 1.2. */
224 thickness?: number;
225 primaryColor?: string;
226 /** @deprecated Use `primaryColor`. */
227 glassColor?: string;
228 /** Rotation speed multiplier. 0 stops it. Default 0.3. */
229 autoRotateSpeed?: number;
230}
231
232const backdropVertexShader = /* glsl */ `
233varying vec2 vUv;
234void main() {
235 vUv = uv;
236 gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
237}
238`;
239
240// Diagonal colored bands: a high-contrast decor that makes the refraction readable through the glass
241const backdropFragmentShader = /* glsl */ `
242uniform float uTime;
243uniform vec3 uBase;
244uniform vec3 uColorA;
245uniform vec3 uColorB;
246varying vec2 vUv;
247
248void main() {
249 float wave = sin((vUv.x * 1.2 + vUv.y * 0.6) * 40.0 + uTime * 0.4);
250 float band = smoothstep(0.2, 0.5, wave);
251 vec3 gradient = mix(uColorA, uColorB, vUv.y);
252 vec3 color = mix(uBase, gradient, band * 0.85);
253 float vignette = 1.0 - smoothstep(0.3, 1.1, length(vUv - 0.5) * 1.6);
254 gl_FragColor = vec4(color * vignette, 1.0);
255 #include <colorspace_fragment>
256}
257`;
258
259type GlassMaterialProps = Required<Omit<GlassmorphismProps, "primaryColor" | "pauseWhenOffscreen" | "lowPowerMode" | "autoRotateSpeed">>;
260
261/**
262 * The knot renders its own refraction buffer (full quality, sees the spheres too); the spheres use
263 * three's shared transmission pass (transmissionSampler): one extra scene render instead of three.
264 */
265function GlassMaterial({ shared, ...props }: GlassMaterialProps & { shared: boolean }) {
266 return (
267 <MeshTransmissionMaterial
268 transmission={props.transmission}
269 roughness={props.roughness}
270 ior={props.ior}
271 chromaticAberration={props.chromaticAberration}
272 thickness={props.thickness}
273 color={props.glassColor}
274 transmissionSampler={shared}
275 samples={6}
276 resolution={512}
277 anisotropicBlur={0.1}
278 distortion={0.2}
279 distortionScale={0.4}
280 temporalDistortion={0.1}
281 backside={false}
282 />
283 );
284}
285
286const GlassScene = memo(function GlassScene({ autoRotateSpeed, ...glass }: Required<Omit<GlassmorphismProps, "primaryColor" | "pauseWhenOffscreen" | "lowPowerMode">>) {
287 const knotRef = useRef<THREE.Mesh>(null);
288 const sphereARef = useRef<THREE.Mesh>(null);
289 const sphereBRef = useRef<THREE.Mesh>(null);
290
291 const knotGeometry = useMemo(() => new THREE.TorusKnotGeometry(1, 0.32, 220, 32), []);
292 const sphereGeometry = useMemo(() => new THREE.SphereGeometry(1, 64, 64), []);
293 const backdropGeometry = useMemo(() => new THREE.PlaneGeometry(30, 16), []);
294 const backdropMaterial = useMemo(
295 () =>
296 new THREE.ShaderMaterial({
297 uniforms: {
298 uTime: { value: 0 },
299 uBase: { value: new THREE.Color("#0b0f1f") },
300 uColorA: { value: new THREE.Color("#7c3aed") },
301 uColorB: { value: new THREE.Color("#c4b5fd") },
302 },
303 vertexShader: backdropVertexShader,
304 fragmentShader: backdropFragmentShader,
305 }),
306 []
307 );
308
309 // The transmission materials are created and disposed by drei/R3F with their meshes
310 useEffect(
311 () => () => {
312 knotGeometry.dispose();
313 sphereGeometry.dispose();
314 backdropGeometry.dispose();
315 backdropMaterial.dispose();
316 },
317 [knotGeometry, sphereGeometry, backdropGeometry, backdropMaterial]
318 );
319
320 useFrame((state, delta) => {
321 const t = state.clock.elapsedTime;
322 backdropMaterial.uniforms.uTime.value = t;
323 const step = delta * autoRotateSpeed;
324
325 // Slow rotation on all three axes, at different rates per shape
326 const knot = knotRef.current;
327 if (knot) {
328 knot.rotation.x += step * 0.6;
329 knot.rotation.y += step * 0.9;
330 knot.rotation.z += step * 0.3;
331 }
332 const sphereA = sphereARef.current;
333 if (sphereA) {
334 sphereA.rotation.y += step * 0.5;
335 sphereA.position.y = 1.3 + Math.sin(t * 0.6) * 0.15;
336 }
337 const sphereB = sphereBRef.current;
338 if (sphereB) {
339 sphereB.rotation.x -= step * 0.7;
340 sphereB.position.y = -1.2 + Math.sin(t * 0.5 + 1.4) * 0.12;
341 }
342 });
343
344 return (
345 <>
346 <mesh geometry={backdropGeometry} material={backdropMaterial} position={[0, 0, -4]} />
347
348 <mesh ref={knotRef} geometry={knotGeometry}>
349 <GlassMaterial {...glass} shared={false} />
350 </mesh>
351 <mesh ref={sphereARef} geometry={sphereGeometry} position={[-2.6, 1.3, -0.8]} scale={0.7}>
352 <GlassMaterial {...glass} shared />
353 </mesh>
354 <mesh ref={sphereBRef} geometry={sphereGeometry} position={[2.5, -1.2, 0.4]} scale={0.45}>
355 <GlassMaterial {...glass} shared />
356 </mesh>
357
358 {/* Reflections from light panels: no HDR file to download */}
359 <Environment resolution={256} frames={1}>
360 <Lightformer form="rect" intensity={2.5} position={[0, 4, 3]} scale={[8, 1.5, 1]} />
361 <Lightformer form="rect" intensity={1.5} position={[-5, 0, 2]} rotation-y={Math.PI / 2} scale={[6, 2, 1]} />
362 <Lightformer form="circle" intensity={2} position={[4, -2, 3]} scale={2} />
363 </Environment>
364 </>
365 );
366});
367
368function GlassmorphismBackground({
369 transmission = 0.95,
370 roughness = 0.15,
371 ior = 1.2,
372 chromaticAberration = 0.04,
373 thickness = 1.2,
374 primaryColor,
375 glassColor = primaryColor ?? "#ffffff",
376 autoRotateSpeed = 0.3,
377 pauseWhenOffscreen,
378 lowPowerMode,
379}: GlassmorphismProps) {
380 return (
381 <BackgroundCanvas pauseWhenOffscreen={pauseWhenOffscreen} lowPowerMode={lowPowerMode} camera={{ position: [0, 0, 6], fov: 40 }} dpr={[1, 1.5]}>
382 <GlassScene
383 transmission={transmission}
384 roughness={roughness}
385 ior={ior}
386 chromaticAberration={chromaticAberration}
387 thickness={thickness}
388 glassColor={glassColor}
389 autoRotateSpeed={autoRotateSpeed}
390 />
391 </BackgroundCanvas>
392 );
393}
394
395export default memo(GlassmorphismBackground);
03

Drop it in a page

Updated live with the settings above.

app/page.tsx
1import GlassmorphismBackground from "@/components/GlassmorphismBackground";
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 <GlassmorphismBackground
8 transmission={0.95}
9 roughness={0.15}
10 ior={1.2}
11 chromaticAberration={0.04}
12 thickness={1.2}
13 autoRotateSpeed={0.3}
14 glassColor="#ffffff"
15 />
16 </div>
17 );
18}
Next componentTopographic Lines→