← All components Next componentMagnetic Vector Field→
Background · Glass
Glass Ribbons Refraction
Diagonal glass blades refracting glowing light with chromatic dispersion; they tilt towards the cursor and catch it on their bevels.
<GlassRibbonsRefraction />Live
Move sideways to tilt the blades
Customize
Background#06070b
Primary#3b4a8c
Accent#e8f0ff
Installation
Use it in your project
Or skip the copy-paste
One command: writes the file and installs the dependencies.
$ npx deepui-cli add glass-ribbons-refraction
01
Install
The 3D packages this component is built on.
$ npm install three @react-three/fiber && npm install -D @types/three
02
Add the component
One self-contained file: create components/GlassRibbonsRefraction.tsx and paste it in.
components/GlassRibbonsRefraction.tsx
1"use client";23import { useEffect, useMemo, useRef, useState, type RefObject } from "react";4import * as THREE from "three";5import { Canvas, useFrame, useThree } from "@react-three/fiber";67/**8 * The shared props API of DeepUI's individual 3D components (not the full-page templates, which keep9 * their own tailored scenes).10 *11 * The props are grouped by concern. A component extends ONLY the groups it really applies, so its12 * type never advertises a knob that does nothing (a card has no particles, a background has no tilt):13 *14 * interface MyCardProps extends CursorProps, TiltProps, MaterialProps, PerformanceProps { … }15 *16 * `Base3DComponentProps` is every group at once, for tooling that handles any component. Same name,17 * same unit and same meaning everywhere; the default values live in DEFAULT_3D_PROPS. These files are18 * inlined into each component's single-file bundle (lib/bundle-source.mjs), only what it uses.19 */2021/** Which rotation axes follow the pointer. "x-only": the object nods (up / down); "y-only": it turns (left / right). */22export type TiltAxis = "both" | "x-only" | "y-only" | "none";2324/** 1. Cursor: how the pointer pulls, pushes and drags the object. */25interface CursorProps {26 /** 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). */27 cursorRadius?: number;28 /** Positive pulls things towards the pointer, negative pushes them away (repulsion, shockwave). Default 1. */29 cursorForce?: number;30 /** How far the object slides towards the pointer, 0 (stays put) to 1 (follows closely). Default 0. */31 magneticStrength?: number;32 /** Share of the remaining distance the motion closes each frame (at 60 fps), 0.01 (heavy, slow) to 1 (instant). Default 0.1. */33 cursorDamping?: number;34}3536/** 2. Tilt and parallax: the object leans towards the pointer, its layers slide against each other. */37interface TiltProps {38 /** Largest lean towards the pointer, in degrees. Default 15. */39 maxTiltAngle?: number;40 /** Axes that follow the pointer. Default "both". */41 tiltAxis?: TiltAxis;42 /** Lean away from the pointer instead of towards it. Default false. */43 invertTilt?: boolean;44 /** How far apart the depth layers slide when the object tilts, 0 (flat) to 2. Default 1. */45 parallaxOffset?: number;46}4748/** 3. Text and 3D typography, for components that draw a label. */49interface Text3DProps {50 /** The label drawn by the component. */51 text?: string;52 /** Scale of the lettering. Default 1. */53 fontSize?: number;54 /** Extrusion depth of 3D letters. Default 0.2. */55 textDepth?: number;56 /** Bevelled, light-catching edges on 3D letters. Default true. */57 bevelEnabled?: boolean;58 /** Custom font: a .woff / .ttf (flat text) or a typeface .json (extruded text). */59 fontUrl?: string;60}6162/** 4. Rendering, materials and glow. */63interface MaterialProps {64 /** Main color of the object. Default "#6366f1". */65 primaryColor?: string;66 /** Color of the glow. Default "#00f0ff". */67 emissiveColor?: string;68 /** Strength of the glow, 0 (none) to 3. Default 1. */69 emissiveIntensity?: number;70 /** 0 (mirror, glass) to 1 (matte). Default 0.3. */71 roughness?: number;72 /** 0 (plastic, organic) to 1 (metal). Default 0.5. */73 metalness?: number;74 /** 0 (opaque) to 1 (clear glass): see-through, refracting surfaces. Default 0. */75 transmission?: number;76 /** Technical wireframe rendering. Default false. */77 wireframe?: boolean;78}7980/** 5. Particles, idle motion and shader animation. */81interface MotionProps {82 /** Number of instanced elements. Default depends on the component. */83 particleCount?: number;84 /** Spin on its own, in radians per second (negative: the other way; 0.5 ≈ one turn in 12 s). Default 0. */85 autoRotateSpeed?: number;86 /** Pulses or ripples per second. Default 1. */87 pulseRate?: number;88 /** Amplitude of the noise deformation, 0 (none) to 2. Default 1. */89 displacementScale?: number;90}9192/** 6. Environment and camera. */93interface EnvironmentProps {94 /** Camera field of view, in degrees. Default depends on the component. */95 cameraFov?: number;96 /** Color of the depth fog. Default "#0a0a0a". */97 fogColor?: string;98 /** Thickness of the fog, 0 (none) to 0.2. Default 0. */99 fogDensity?: number;100}101102/** 7. Performance and accessibility. */103interface PerformanceProps {104 /** Lighter rendering for weak devices: pixel ratio 1, fewer instances, smaller environment maps. Default false. */105 lowPowerMode?: boolean;106 /** Under the OS "reduce motion" setting, stop idle spin, pulses and deformation (pointer feedback stays). Default true. */107 respectReducedMotion?: boolean;108 /** Stop the render loop while the component is scrolled out of view. Default true. */109 pauseWhenOffscreen?: boolean;110}111112/** Every group at once. Components extend only the groups they apply (see the top of this file). */113interface Base3DComponentProps114 extends CursorProps,115 TiltProps,116 Text3DProps,117 MaterialProps,118 MotionProps,119 EnvironmentProps,120 PerformanceProps {}121122type Defaults = Required<Omit<Base3DComponentProps, "text" | "fontUrl" | "particleCount" | "cameraFov">>;123124/** The values a prop takes when it is left out. A component may override one, and then documents it. */125const DEFAULT_3D_PROPS: Defaults = {126 cursorRadius: 220,127 cursorForce: 1,128 magneticStrength: 0,129 cursorDamping: 0.1,130 maxTiltAngle: 15,131 tiltAxis: "both",132 invertTilt: false,133 parallaxOffset: 1,134 fontSize: 1,135 textDepth: 0.2,136 bevelEnabled: true,137 primaryColor: "#6366f1",138 emissiveColor: "#00f0ff",139 emissiveIntensity: 1,140 roughness: 0.3,141 metalness: 0.5,142 transmission: 0,143 wireframe: false,144 autoRotateSpeed: 0,145 pulseRate: 1,146 displacementScale: 1,147 fogColor: "#0a0a0a",148 fogDensity: 0,149 lowPowerMode: false,150 respectReducedMotion: true,151 pauseWhenOffscreen: true,152};153154/**155 * The shared behaviour behind the props of ./types: pointer inertia, tilt, magnetic pull, idle spin,156 * the OS "reduce motion" setting and the off-screen pause. Inlined into each component's bundle.157 */158159/** True while the OS asks for reduced motion; follows the setting live. */160function usePrefersReducedMotion(): boolean {161 const [reduced, setReduced] = useState(false);162 useEffect(() => {163 const query = window.matchMedia("(prefers-reduced-motion: reduce)");164 const sync = () => setReduced(query.matches);165 sync();166 query.addEventListener("change", sync);167 return () => query.removeEventListener("change", sync);168 }, []);169 return reduced;170}171172/**173 * The <Canvas> frameloop for `pauseWhenOffscreen`: "never" while the element is out of view. Put the ref174 * on the element that wraps the canvas (outside it: this hook runs in the component, not in the scene).175 */176function useOffscreenFrameloop(ref: RefObject<HTMLElement | null>, pauseWhenOffscreen: boolean = DEFAULT_3D_PROPS.pauseWhenOffscreen): "always" | "never" {177 // In view at first: some WebGL backends show an opaque canvas if it is paused before its first frame178 const [inView, setInView] = useState(true);179 useEffect(() => {180 const el = ref.current;181 if (!el || !pauseWhenOffscreen) return undefined;182 const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting));183 observer.observe(el);184 return () => observer.disconnect();185 }, [ref, pauseWhenOffscreen]);186 return !pauseWhenOffscreen || inView ? "always" : "never";187}188189/**190 * Shared GLSL noise functions, injected into the background shaders as strings.191 *192 * Both are the classic webgl-noise implementations by Ian McEwan and Stefan193 * Gustavson (Ashima Arts), MIT License — https://github.com/ashima/webgl-noise194 */195196/** 3D simplex noise: `float snoise(vec3 v)`, returns roughly -1..1. */197const SIMPLEX_3D = /* glsl */ `198vec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }199vec4 mod289(vec4 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }200vec4 permute(vec4 x) { return mod289(((x * 34.0) + 10.0) * x); }201vec4 taylorInvSqrt(vec4 r) { return 1.79284291400159 - 0.85373472095314 * r; }202203float snoise(vec3 v) {204 const vec2 C = vec2(1.0 / 6.0, 1.0 / 3.0);205 const vec4 D = vec4(0.0, 0.5, 1.0, 2.0);206207 vec3 i = floor(v + dot(v, C.yyy));208 vec3 x0 = v - i + dot(i, C.xxx);209210 vec3 g = step(x0.yzx, x0.xyz);211 vec3 l = 1.0 - g;212 vec3 i1 = min(g.xyz, l.zxy);213 vec3 i2 = max(g.xyz, l.zxy);214215 vec3 x1 = x0 - i1 + C.xxx;216 vec3 x2 = x0 - i2 + C.yyy;217 vec3 x3 = x0 - D.yyy;218219 i = mod289(i);220 vec4 p = permute(permute(permute(221 i.z + vec4(0.0, i1.z, i2.z, 1.0))222 + i.y + vec4(0.0, i1.y, i2.y, 1.0))223 + i.x + vec4(0.0, i1.x, i2.x, 1.0));224225 float n_ = 0.142857142857;226 vec3 ns = n_ * D.wyz - D.xzx;227228 vec4 j = p - 49.0 * floor(p * ns.z * ns.z);229 vec4 x_ = floor(j * ns.z);230 vec4 y_ = floor(j - 7.0 * x_);231232 vec4 x = x_ * ns.x + ns.yyyy;233 vec4 y = y_ * ns.x + ns.yyyy;234 vec4 h = 1.0 - abs(x) - abs(y);235236 vec4 b0 = vec4(x.xy, y.xy);237 vec4 b1 = vec4(x.zw, y.zw);238 vec4 s0 = floor(b0) * 2.0 + 1.0;239 vec4 s1 = floor(b1) * 2.0 + 1.0;240 vec4 sh = -step(h, vec4(0.0));241242 vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;243 vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww;244245 vec3 p0 = vec3(a0.xy, h.x);246 vec3 p1 = vec3(a0.zw, h.y);247 vec3 p2 = vec3(a1.xy, h.z);248 vec3 p3 = vec3(a1.zw, h.w);249250 vec4 norm = taylorInvSqrt(vec4(dot(p0, p0), dot(p1, p1), dot(p2, p2), dot(p3, p3)));251 p0 *= norm.x;252 p1 *= norm.y;253 p2 *= norm.z;254 p3 *= norm.w;255256 vec4 m = max(0.5 - vec4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0);257 m = m * m;258 return 105.0 * dot(m * m, vec4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3)));259}260`;261262// GLSL shared by the procedural backgrounds. Every fragment shader starts with PRELUDE, then defines263// main(). Coordinates: `vUv` is 0..1 across the canvas (y up); aspectCoord() gives a centered space where264// the canvas is 1 unit tall and `uAspect` units wide, so circles stay round on any screen.265266const FULLSCREEN_VERTEX = /* glsl */ `267varying vec2 vUv;268void main() {269 vUv = uv;270 gl_Position = vec4(position.xy, 0.0, 1.0);271}272`;273274const UNIFORMS = /* glsl */ `275uniform float uTime; // seconds, already multiplied by \`speed\`276uniform vec2 uResolution; // drawing buffer size, px277uniform float uAspect; // width / height278uniform vec2 uMouse; // smoothed pointer, 0..1279uniform vec2 uMouseVelocity; // smoothed pointer velocity, canvas units per second280uniform float uInteract; // 0..1 presence of the pointer (0 when \`interactive\` is false)281uniform float uPress; // 0..1 while a button is held282uniform float uScale; // pattern size multiplier283uniform vec3 uColorBg;284uniform vec3 uColorPrimary;285uniform vec3 uColorAccent;286uniform sampler2D uTrail; // cursor simulation (see TrailSimulation), when the background has one287uniform vec2 uTrailTexel; // 1 / its resolution288varying vec2 vUv;289`;290291const HELPERS = /* glsl */ `292const float PI = 3.14159265;293294vec2 aspectCoord(vec2 uv) { return (uv - 0.5) * vec2(uAspect, 1.0); }295vec2 mouseCoord() { return aspectCoord(uMouse); }296vec2 mouseVelocity() { return uMouseVelocity * vec2(uAspect, 1.0); }297298mat2 rot2(float a) {299 float c = cos(a);300 float s = sin(a);301 return mat2(c, s, -s, c);302}303304// Hashes without sine (Dave Hoskins, MIT): stable on every GPU305float hash12(vec2 p) {306 vec3 p3 = fract(vec3(p.xyx) * 0.1031);307 p3 += dot(p3, p3.yzx + 33.33);308 return fract((p3.x + p3.y) * p3.z);309}310vec2 hash22(vec2 p) {311 vec3 p3 = fract(vec3(p.xyx) * vec3(0.1031, 0.1030, 0.0973));312 p3 += dot(p3, p3.yzx + 33.33);313 return fract((p3.xx + p3.yz) * p3.zy);314}315316// Fractional Brownian motion over simplex noise, up to 6 octaves317float fbm(vec3 p, int octaves) {318 float sum = 0.0;319 float amp = 0.5;320 for (int i = 0; i < 6; i++) {321 if (i >= octaves) break;322 sum += amp * snoise(p);323 p = p * 2.02 + vec3(17.1, -3.7, 5.3);324 amp *= 0.5;325 }326 return sum;327}328329// Gradient of the ripple simulation's height at uv (central differences)330vec2 trailGradient(vec2 uv) {331 float l = texture2D(uTrail, uv - vec2(uTrailTexel.x, 0.0)).r;332 float r = texture2D(uTrail, uv + vec2(uTrailTexel.x, 0.0)).r;333 float d = texture2D(uTrail, uv - vec2(0.0, uTrailTexel.y)).r;334 float u = texture2D(uTrail, uv + vec2(0.0, uTrailTexel.y)).r;335 return vec2(r - l, u - d) * 0.5;336}337338// Breaks the 8-bit banding of slow gradients; never negative (the sRGB conversion would turn it black)339vec3 dither(vec3 color) {340 return max(color + (hash12(gl_FragCoord.xy) - 0.5) / 255.0, 0.0);341}342`;343344const PRELUDE = UNIFORMS + SIMPLEX_3D + HELPERS;345346const SIM_UNIFORMS = /* glsl */ `347uniform sampler2D uPrev;348uniform vec2 uTexel;349uniform float uAspect;350uniform vec2 uMouse;351uniform vec2 uMouseVelocity;352uniform float uInteract;353uniform float uDt;354varying vec2 vUv;355`;356357/** Ripple: a damped 2D wave equation; the moving cursor drops into it like a finger in water. */358const RIPPLE_FRAGMENT = /* glsl */ `359${SIM_UNIFORMS}360void main() {361 vec2 uv = vUv;362 vec4 here = texture2D(uPrev, uv);363 float sum = texture2D(uPrev, uv + vec2(uTexel.x, 0.0)).r + texture2D(uPrev, uv - vec2(uTexel.x, 0.0)).r364 + texture2D(uPrev, uv + vec2(0.0, uTexel.y)).r + texture2D(uPrev, uv - vec2(0.0, uTexel.y)).r;365 float h = (sum * 0.5 - here.g) * 0.975;366367 vec2 d = (uv - uMouse) * vec2(uAspect, 1.0);368 float speed = length(uMouseVelocity * vec2(uAspect, 1.0));369 h += exp(-dot(d, d) / 0.0009) * min(speed, 1.2) * uInteract * 0.012;370 gl_FragColor = vec4(clamp(h, -1.0, 1.0), here.r, 0.0, 1.0);371}372`;373374/**375 * Props shared by the procedural backgrounds (FluidSmokeDrift, FerrofluidTopography, …). Every one of376 * them is a single shader: no image, no video, no external asset. Changing a prop live never recompiles377 * the shader: colors, speed and scale are uniforms.378 */379interface DeepBackgroundProps extends Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode" | "respectReducedMotion"> {380 /** React to the pointer. false removes the listeners and lets every cursor force ease back to 0. Default true. */381 interactive?: boolean;382 /** Palette: [background, primary, accent]. The accent falls back to the component's own. */383 colors?: [string, string, string?];384 /** Animation speed multiplier; changing it live never makes the animation jump. Default 1. */385 speed?: number;386 /** Size of the patterns, grain or cells: 2 makes them twice as large. Default 1. */387 scale?: number;388 /** Extra classes for the container (absolutely positioned, filling its parent). */389 className?: string;390}391392type BackgroundPalette = readonly [string, string, string];393394const DEEP_BACKGROUND_DEFAULTS = {395 interactive: true,396 speed: 1,397 scale: 1,398} as const;399400/**401 * Memory of the cursor, simulated on the GPU at low resolution and handed to the shader as `uTrail`.402 * "ripple": a damped wave equation (r = height, g = previous height): circular waves spreading out.403 */404type TrailSimulation = "ripple";405406/** The cursor as the shaders see it. Read inside useFrame: pointer moves never re-render React. */407interface PointerPhysics {408 /** Smoothed position in the canvas, 0..1 (y up). */409 position: THREE.Vector2;410 /** Smoothed velocity, in canvas units (0..1) per second. */411 velocity: THREE.Vector2;412 /** 0..1: eases to 1 while the pointer is over the canvas (and `interactive`), back to 0 otherwise. */413 strength: number;414 /** 0..1: eases to 1 while a button or a finger is down. */415 press: number;416}417418interface RawPointer {419 x: number;420 y: number;421 inside: boolean;422 down: boolean;423 seen: boolean;424}425426const FOLLOW = 14; // damp rate of the position427428const VELOCITY_FOLLOW = 8;429430const STRENGTH_FOLLOW = 3.5; // forces fade in and out over ~half a second431432/**433 * Pointer physics shared by the procedural backgrounds: smoothed position, smoothed velocity and an434 * eased presence. The canvas has `pointer-events: none` (the page above it stays clickable), so the435 * pointer is read from window listeners. With `interactive` false there is no listener at all and436 * every force eases back to 0, leaving the autonomous animation alone.437 */438function usePointerPhysics(interactive: boolean): RefObject<PointerPhysics> {439 const gl = useThree((state) => state.gl);440 const raw = useRef<RawPointer>({ x: 0.5, y: 0.5, inside: false, down: false, seen: false });441 const physics = useRef<PointerPhysics>({ position: new THREE.Vector2(0.5, 0.5), velocity: new THREE.Vector2(), strength: 0, press: 0 });442 const previous = useRef(new THREE.Vector2(0.5, 0.5));443444 useEffect(() => {445 const p = raw.current;446 if (!interactive) {447 p.inside = false;448 p.down = false;449 return undefined;450 }451 const el = gl.domElement;452 const move = (event: PointerEvent) => {453 const rect = el.getBoundingClientRect();454 if (!rect.width || !rect.height) return;455 p.x = (event.clientX - rect.left) / rect.width;456 p.y = 1 - (event.clientY - rect.top) / rect.height;457 p.inside = p.x >= 0 && p.x <= 1 && p.y >= 0 && p.y <= 1;458 if (!p.seen) {459 // First contact: start from the pointer instead of sweeping in from the center460 p.seen = true;461 physics.current.position.set(p.x, p.y);462 previous.current.set(p.x, p.y);463 }464 };465 const down = (event: PointerEvent) => {466 move(event);467 p.down = true;468 };469 const up = () => {470 p.down = false;471 };472 const leave = () => {473 p.inside = false;474 p.down = false;475 };476 window.addEventListener("pointermove", move, { passive: true });477 window.addEventListener("pointerdown", down, { passive: true });478 window.addEventListener("pointerup", up, { passive: true });479 window.addEventListener("pointercancel", leave, { passive: true });480 document.documentElement.addEventListener("pointerleave", leave);481 window.addEventListener("blur", leave);482 return () => {483 window.removeEventListener("pointermove", move);484 window.removeEventListener("pointerdown", down);485 window.removeEventListener("pointerup", up);486 window.removeEventListener("pointercancel", leave);487 document.documentElement.removeEventListener("pointerleave", leave);488 window.removeEventListener("blur", leave);489 };490 }, [gl, interactive]);491492 useFrame((_, delta) => {493 const dt = Math.min(delta, 1 / 20);494 const p = raw.current;495 const s = physics.current;496 const damp = THREE.MathUtils.damp;497 s.position.set(damp(s.position.x, p.x, FOLLOW, dt), damp(s.position.y, p.y, FOLLOW, dt));498 const vx = dt > 0 ? (s.position.x - previous.current.x) / dt : 0;499 const vy = dt > 0 ? (s.position.y - previous.current.y) / dt : 0;500 previous.current.copy(s.position);501 const active = interactive && p.inside;502 s.velocity.set(damp(s.velocity.x, active ? vx : 0, VELOCITY_FOLLOW, dt), damp(s.velocity.y, active ? vy : 0, VELOCITY_FOLLOW, dt));503 s.strength = damp(s.strength, active ? 1 : 0, STRENGTH_FOLLOW, dt);504 s.press = damp(s.press, active && p.down ? 1 : 0, STRENGTH_FOLLOW * 2, dt);505 });506507 return physics;508}509510interface BackgroundUniforms {511 uTime: THREE.IUniform<number>;512 uResolution: THREE.IUniform<THREE.Vector2>;513 uAspect: THREE.IUniform<number>;514 uMouse: THREE.IUniform<THREE.Vector2>;515 uMouseVelocity: THREE.IUniform<THREE.Vector2>;516 uInteract: THREE.IUniform<number>;517 uPress: THREE.IUniform<number>;518 uScale: THREE.IUniform<number>;519 uColorBg: THREE.IUniform<THREE.Color>;520 uColorPrimary: THREE.IUniform<THREE.Color>;521 uColorAccent: THREE.IUniform<THREE.Color>;522 uTrail: THREE.IUniform<THREE.Texture | null>;523 uTrailTexel: THREE.IUniform<THREE.Vector2>;524}525526interface SimUniforms {527 uPrev: THREE.IUniform<THREE.Texture | null>;528 uTexel: THREE.IUniform<THREE.Vector2>;529 uAspect: THREE.IUniform<number>;530 uMouse: THREE.IUniform<THREE.Vector2>;531 uMouseVelocity: THREE.IUniform<THREE.Vector2>;532 uInteract: THREE.IUniform<number>;533 uDt: THREE.IUniform<number>;534}535536const SIM_STEP = 1 / 60; // fixed step: waves travel at the same speed at 60, 120 or 144 fps537538const SIM_SIZE: Record<TrailSimulation, number> = { ripple: 288 }; // px on the long side539540/**541 * Ping-pong render targets at low resolution, stepped before the frame is drawn. Writes its latest542 * state into `target.uTrail`.543 */544function useTrailSimulation(kind: TrailSimulation | undefined, physics: RefObject<PointerPhysics>, target: BackgroundUniforms) {545 const gl = useThree((state) => state.gl);546 const width = useThree((state) => state.size.width);547 const height = useThree((state) => state.size.height);548 const aspect = width / Math.max(height, 1);549550 // Resolution follows the canvas shape, rounded so small resizes keep the current simulation551 const long = kind ? SIM_SIZE[kind] : 0;552 const simW = kind ? Math.max(16, Math.round((aspect >= 1 ? long : long * aspect) / 8) * 8) : 0;553 const simH = kind ? Math.max(16, Math.round((aspect >= 1 ? long / aspect : long) / 8) * 8) : 0;554555 const sim = useMemo(() => {556 if (!kind) return null;557 const make = () =>558 new THREE.WebGLRenderTarget(simW, simH, {559 type: THREE.HalfFloatType,560 format: THREE.RGBAFormat,561 minFilter: THREE.LinearFilter,562 magFilter: THREE.LinearFilter,563 wrapS: THREE.ClampToEdgeWrapping,564 wrapT: THREE.ClampToEdgeWrapping,565 depthBuffer: false,566 stencilBuffer: false,567 });568 const uniforms: SimUniforms = {569 uPrev: { value: null },570 uTexel: { value: new THREE.Vector2(1 / simW, 1 / simH) },571 uAspect: { value: 1 },572 uMouse: { value: new THREE.Vector2(0.5, 0.5) },573 uMouseVelocity: { value: new THREE.Vector2() },574 uInteract: { value: 0 },575 uDt: { value: SIM_STEP },576 };577 const material = new THREE.ShaderMaterial({578 uniforms: uniforms as unknown as Record<string, THREE.IUniform>,579 vertexShader: FULLSCREEN_VERTEX,580 fragmentShader: RIPPLE_FRAGMENT,581 depthTest: false,582 depthWrite: false,583 });584 const geometry = new THREE.PlaneGeometry(2, 2);585 const quad = new THREE.Mesh(geometry, material);586 quad.frustumCulled = false;587 const scene = new THREE.Scene();588 scene.add(quad);589 return { targets: [make(), make()] as [THREE.WebGLRenderTarget, THREE.WebGLRenderTarget], uniforms, material, geometry, scene, camera: new THREE.Camera(), read: 0, carry: 0 };590 }, [kind, simW, simH]);591592 useEffect(() => {593 if (!sim) return undefined;594 target.uTrailTexel.value.set(1 / simW, 1 / simH);595 return () => {596 sim.targets.forEach((t) => t.dispose());597 sim.material.dispose();598 sim.geometry.dispose();599 if (sim.targets.some((t) => t.texture === target.uTrail.value)) target.uTrail.value = null;600 };601 }, [sim, simW, simH, target]);602603 useFrame((_, delta) => {604 if (!sim) return;605 const p = physics.current;606 const u = sim.uniforms;607 u.uAspect.value = aspect;608 u.uMouse.value.copy(p.position);609 u.uMouseVelocity.value.copy(p.velocity);610 u.uInteract.value = p.strength;611612 // Fixed steps, at most 3 per frame (a background tab coming back must not fast-forward for seconds)613 sim.carry = Math.min(sim.carry + delta, SIM_STEP * 3);614 const previousTarget = gl.getRenderTarget();615 while (sim.carry >= SIM_STEP) {616 sim.carry -= SIM_STEP;617 const read = sim.targets[sim.read];618 const write = sim.targets[1 - sim.read];619 u.uPrev.value = read.texture;620 gl.setRenderTarget(write);621 gl.render(sim.scene, sim.camera);622 sim.read = 1 - sim.read;623 }624 gl.setRenderTarget(previousTarget);625 target.uTrail.value = sim.targets[sim.read].texture;626 });627}628629interface ShaderPlaneProps {630 fragmentShader: string;631 palette: BackgroundPalette;632 interactive: boolean;633 speed: number;634 scale: number;635 still: boolean;636 simulation?: TrailSimulation;637}638639function ShaderPlane({ fragmentShader, palette, interactive, speed, scale, still, simulation }: ShaderPlaneProps) {640 const physics = usePointerPhysics(interactive);641 // Smoothed so a slider drag never makes the patterns jump (starts at the initial value)642 const scaleTarget = useRef(Math.max(0.05, scale));643644 // Compiled once per shader; every prop below only updates uniforms645 const { material, uniforms } = useMemo(() => {646 const u: BackgroundUniforms = {647 uTime: { value: 0 },648 uResolution: { value: new THREE.Vector2(1, 1) },649 uAspect: { value: 1 },650 uMouse: { value: new THREE.Vector2(0.5, 0.5) },651 uMouseVelocity: { value: new THREE.Vector2() },652 uInteract: { value: 0 },653 uPress: { value: 0 },654 uScale: { value: scaleTarget.current },655 uColorBg: { value: new THREE.Color() },656 uColorPrimary: { value: new THREE.Color() },657 uColorAccent: { value: new THREE.Color() },658 uTrail: { value: null },659 uTrailTexel: { value: new THREE.Vector2(1, 1) },660 };661 const m = new THREE.ShaderMaterial({662 uniforms: u as unknown as Record<string, THREE.IUniform>,663 vertexShader: FULLSCREEN_VERTEX,664 fragmentShader: PRELUDE + fragmentShader + "\n",665 depthTest: false,666 depthWrite: false,667 });668 return { material: m, uniforms: u };669 }, [fragmentShader]);670 const geometry = useMemo(() => new THREE.PlaneGeometry(2, 2), []);671672 useEffect(() => () => material.dispose(), [material]);673 useEffect(() => () => geometry.dispose(), [geometry]);674675 const [background, primary, accent] = palette;676 useEffect(() => {677 uniforms.uColorBg.value.set(background);678 uniforms.uColorPrimary.value.set(primary);679 uniforms.uColorAccent.value.set(accent);680 }, [uniforms, background, primary, accent]);681682 useEffect(() => {683 scaleTarget.current = Math.max(0.05, scale);684 }, [scale]);685686 useTrailSimulation(simulation, physics, uniforms);687688 useFrame((state, delta) => {689 const dt = Math.min(delta, 1 / 20);690 const u = uniforms;691 // Time integrates the speed: changing it live changes the pace, never the position in the animation692 if (!still) u.uTime.value += dt * speed;693 const { width, height } = state.size;694 u.uResolution.value.set(width * state.viewport.dpr, height * state.viewport.dpr);695 u.uAspect.value = width / Math.max(height, 1);696 u.uScale.value = THREE.MathUtils.damp(u.uScale.value, scaleTarget.current, 6, dt);697 const p = physics.current;698 u.uMouse.value.copy(p.position);699 u.uMouseVelocity.value.copy(p.velocity);700 u.uInteract.value = p.strength;701 u.uPress.value = p.press;702 });703704 return <mesh geometry={geometry} material={material} frustumCulled={false} />;705}706707interface ShaderBackgroundProps extends DeepBackgroundProps {708 /** Body of the fragment shader: PRELUDE (uniforms, noise, helpers) is prepended. */709 fragmentShader: string;710 /** The component's own palette, used for any color left out of `colors`. */711 defaultColors: BackgroundPalette;712 simulation?: TrailSimulation;713}714715/**716 * One full-screen shader behind the page: fills its positioned parent, never catches clicks, pauses717 * off-screen, freezes its clock under "reduce motion" (the cursor still reacts) and disposes every GPU718 * resource on unmount.719 */720function ShaderBackground({721 fragmentShader,722 defaultColors,723 simulation,724 interactive = DEEP_BACKGROUND_DEFAULTS.interactive,725 colors,726 speed = DEEP_BACKGROUND_DEFAULTS.speed,727 scale = DEEP_BACKGROUND_DEFAULTS.scale,728 className = "",729 pauseWhenOffscreen = DEFAULT_3D_PROPS.pauseWhenOffscreen,730 lowPowerMode = DEFAULT_3D_PROPS.lowPowerMode,731 respectReducedMotion = DEFAULT_3D_PROPS.respectReducedMotion,732}: ShaderBackgroundProps) {733 const container = useRef<HTMLDivElement>(null);734 const frameloop = useOffscreenFrameloop(container, pauseWhenOffscreen);735 const reduced = usePrefersReducedMotion();736 const palette: BackgroundPalette = [colors?.[0] ?? defaultColors[0], colors?.[1] ?? defaultColors[1], colors?.[2] ?? defaultColors[2]];737738 return (739 <div ref={container} className={`pointer-events-none absolute inset-0 overflow-hidden ${className}`} style={{ background: palette[0] }} aria-hidden="true">740 <Canvas741 dpr={lowPowerMode ? 1 : [1, 1.75]}742 frameloop={frameloop}743 gl={{ antialias: false, alpha: false, powerPreference: "high-performance" }}744 style={{ pointerEvents: "none" }}745 >746 <ShaderPlane747 fragmentShader={fragmentShader}748 palette={palette}749 interactive={interactive}750 speed={speed}751 scale={scale}752 still={respectReducedMotion && reduced}753 simulation={simulation}754 />755 </Canvas>756 </div>757 );758}759760export type { DeepBackgroundProps };761762const COLORS: BackgroundPalette = ["#06070b", "#3b4a8c", "#e8f0ff"];763764// Diagonal blades of glass over slow, glowing light blobs. Each blade is a lens: the scene behind it is765// sampled through an offset that grows across the blade's width (its thickness profile) and with its766// tilt, three times with a slightly different index per channel (dispersion). The blades tilt towards the767// pointer, more the further they are from it, and their bevels catch the light on the tilted side.768const FRAGMENT = /* glsl */ `769const float ANGLE = -0.56;770771vec3 scene(vec2 p) {772 vec3 color = uColorBg;773 for (int i = 0; i < 4; i++) {774 float fi = float(i);775 vec2 c = vec2(776 sin(uTime * 0.13 * (fi + 1.0) + fi * 1.7) * 0.3 * uAspect,777 cos(uTime * 0.11 * (fi + 1.3) + fi * 2.3) * 0.32778 );779 float g = exp(-dot(p - c, p - c) / (0.018 + 0.01 * fi));780 color += mix(uColorPrimary, uColorAccent * 0.45, mod(fi, 2.0)) * g * 0.75;781 }782 return color;783}784785void main() {786 vec2 p = aspectCoord(vUv);787 mat2 toBlade = rot2(ANGLE);788 mat2 toScreen = rot2(-ANGLE);789 vec2 r = toBlade * p;790791 float width = 0.15 * uScale;792 float drift = uTime * 0.02;793 float u = r.x / width + drift;794 float id = floor(u);795 float local = fract(u);796797 float bladeCenter = (id + 0.5 - drift) * width;798 vec2 mr = toBlade * mouseCoord();799 float tilt = 0.35 * sin(id * 1.7 + uTime * 0.25) + uInteract * clamp((mr.x - bladeCenter) * 2.2, -1.2, 1.2);800801 float across = local * 2.0 - 1.0;802 vec2 offset = toScreen * vec2(across * 0.06 + tilt * 0.05, across * tilt * 0.02);803 vec3 color = vec3(804 scene(p + offset * 1.0).r,805 scene(p + offset * 1.08).g,806 scene(p + offset * 1.16).b807 );808809 // Bevels: the edge facing the tilt lights up, the other one darkens810 float edge = min(local, 1.0 - local);811 float bevel = 1.0 - smoothstep(0.0, 0.07, edge);812 float lit = sign(across) * tilt;813 color += uColorAccent * bevel * (0.06 + 0.3 * max(lit, 0.0));814 color *= 1.0 - bevel * 0.35 * max(-lit, 0.0);815 float fw = fwidth(u);816 color += vec3(1.0) * (1.0 - smoothstep(0.0, fw * 1.5, edge)) * 0.07;817 // A soft sheen sliding across each blade with its tilt818 color += uColorAccent * pow(max(0.0, 1.0 - abs(across - tilt * 0.6)), 8.0) * 0.07;819 color *= 1.0 - 0.3 * dot(p, p);820 gl_FragColor = vec4(dither(color), 1.0);821 #include <colorspace_fragment>822}823`;824825/** Kinetic glass blades refracting glowing light; they tilt towards the pointer and catch it on their bevels. */826export default function GlassRibbonsRefraction(props: DeepBackgroundProps) {827 return <ShaderBackground {...props} fragmentShader={FRAGMENT} defaultColors={COLORS} />;828}
03
Drop it in a page
Updated live with the settings above.
app/page.tsx
1import GlassRibbonsRefraction from "@/components/GlassRibbonsRefraction";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 <GlassRibbonsRefraction8 speed={1}9 scale={1}10 background="#06070b"11 primary="#3b4a8c"12 accent="#e8f0ff"13 interactive14 />15 </div>16 );17}