Copied!
Background

Physics glow spheres

Eighteen glossy glowing spheres huddle in the middle, knock into each other, get shoved aside by the pointer and are lit by three coloured lights that circle them; a click changes the palette.

← Library

Element · Vanilla JS + WebGLUpdated November 6, 2026

3DElementVanilla JS + WebGL

Live preview needs JavaScript. The code below works without any dependencies.

Prompt for your AI assistant

Paste this into Claude, Cursor or ChatGPT. The settings update as you move the controls above.

Build "Physics glow spheres" for my site using the Enrichr Library element at https://enrichr.dev/elements/physics-glow-spheres.html.

Read the machine-readable spec and source at https://enrichr.dev/elements/physics-glow-spheres.json (markup, CSS, JavaScript, parameters).
Requirements: vanilla JavaScript and CSS, no new dependencies; keep the behaviour of the source unchanged; respect prefers-reduced-motion; work on touch screens; keep it accessible.

Settings:
- scheme: enrichr
- lights: 1
- orbit: 0.4
- pushStrength: 25
- pushRadius: 4.5
- glow: 0.65
- fog: 0.012
- light1: #fbf8f1
- light2: #e6ff55
- light3: #4b1a9a
- background: #0c1e18

Verify: reduced motion shows no movement, it works at 375px wide, there are no console errors, and scrolling stays smooth.

The same spec as JSON, for tools that read it directly: /elements/physics-glow-spheres.json.

Code

Mount it on an element that contains the markup. It returns an object with update(options) and destroy().

HTML

<div class="ef-orbs"><canvas class="ef-orbs__c" role="img" aria-label="Eighteen glossy glowing spheres huddled in the middle, pushed apart by the pointer and lit by three coloured lights that circle them"></canvas><button class="ef-orbs__btn" type="button">Change palette</button><span class="ef-orbs__live" aria-live="polite"></span></div>

CSS

/* Enrichr Library · https://enrichr.dev */
.ef-orbs { position: relative; width: 100%; min-height: 24rem; overflow: hidden; border-radius: 1rem; background: radial-gradient(circle at 50% 50%, rgba(230, 255, 85, 0.14), rgba(230, 255, 85, 0) 42%), var(--ef-orbs-bg, #0c1e18); cursor: pointer; touch-action: pan-y; -webkit-user-select: none; user-select: none; -webkit-tap-highlight-color: transparent; }
.ef-orbs .ef-orbs__c { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
.ef-orbs .ef-orbs__btn { position: absolute; top: 1rem; left: 50%; z-index: 1; transform: translateX(-50%); margin: 0; padding: 0.55rem 1.15rem; border-radius: 999px; border: 1px solid rgba(251, 248, 241, 0.16); background: rgba(12, 30, 24, 0.82); color: #fbf8f1; font: 500 0.75rem/1 'Parkinsans', 'Space Grotesk', sans-serif; letter-spacing: 0.02em; cursor: pointer; -webkit-backdrop-filter: blur(12px); backdrop-filter: blur(12px); box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.3), 0 8px 10px -6px rgba(0, 0, 0, 0.3); transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), box-shadow 0.3s cubic-bezier(0.4, 0, 0.2, 1), border-color 0.3s cubic-bezier(0.4, 0, 0.2, 1), background-color 0.3s cubic-bezier(0.4, 0, 0.2, 1); }
.ef-orbs .ef-orbs__btn:hover { transform: translateX(-50%) translateY(-2px); background: rgba(12, 30, 24, 0.95); border-color: rgba(251, 248, 241, 0.3); box-shadow: 0 20px 35px -5px rgba(0, 0, 0, 0.4); }
.ef-orbs .ef-orbs__btn:focus-visible { outline: 2px solid #e6ff55; outline-offset: 3px; }
.ef-orbs .ef-orbs__live { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; }
@media (prefers-reduced-motion: reduce) { .ef-orbs .ef-orbs__btn { transition: none; } .ef-orbs .ef-orbs__btn:hover { transform: translateX(-50%); } }

JavaScript

// Enrichr Library · https://enrichr.dev
// Physics glow spheres: eighteen glossy, glowing spheres huddle in the middle of the box. A centring force pulls back any
// sphere that drifts more than about 5.5 units out, the pointer shoves nearby spheres away, and the spheres knock into
// each other. Three coloured point lights circle the group on a tilted ring. Click (or the button) cycles the palette and
// the colours ease across.
// No libraries. The physics is a small sphere solver written to match cannon.js as the original pen used it: fixed 1/60 s
// steps (up to three per frame), contacts solved like cannon's default contact (Spook stiffness 1e7, relaxation 3, no
// bounce, ten Gauss-Seidel passes), linear damping 0.35, a centring force of -0.6 x position once a sphere is more than
// root 30 from the centre, and a pointer push of (1 - distance / radius) x strength inside the push radius, plus a
// 1.5-unit pointer sphere that the balls collide with. The picture is one WebGL1 fragment shader that ray-traces the
// spheres analytically (nearest hit per pixel, edges smoothed over one pixel) and shades them like the original
// MeshPhysicalMaterial (metalness 0.85, roughness 0.15, clearcoat 1, emissive glow) under the three point lights and a
// soft ambient, with ACES filmic tone mapping (exposure 1.3) and exponential fog towards the background colour.
// Reduced motion settles the spheres first, then draws one still frame (the palette button still works). The loop
// pauses off screen and in hidden tabs. Without WebGL the CSS background stays.
// mount(root, { scheme (colour palette), lights ("1" on, "0" off), orbit (light orbit speed, radians a second),
//               pushStrength (pointer push), pushRadius (pointer reach, scene units), glow (emissive strength),
//               fog (fog density), light1, light2, light3 (light colours), background (background and fog colour) })
function mount(root, o) {
  var reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
  var wrap = root.querySelector(".ef-orbs");
  var canvas = root.querySelector(".ef-orbs__c");
  var btn = root.querySelector(".ef-orbs__btn");
  var live = root.querySelector(".ef-orbs__live");
  var opts = {}, raf = 0, visible = true, io = null, ro = null, destroyed = false, last = 0;
  var gl = null, prog = null, vb = null, u = {}, ok = false;

  var N = 18, R = 1.1, PR = 1.5, H = 1 / 60, CAMZ = 35, TANH = Math.tan(9 * Math.PI / 180);
  var SA = 4 / (H * (1 + 4 * 3)), SB = (4 * 3) / (1 + 4 * 3), SEPS = 4 / (H * H * 1e7 * (1 + 4 * 3));
  var DAMP = Math.pow(1 - 0.35, H), MAXC = N * (N - 1) / 2 + N;
  var px = new Float64Array(N), py = new Float64Array(N), pz = new Float64Array(N);
  var vx = new Float64Array(N), vy = new Float64Array(N), vz = new Float64Array(N);
  var fx = new Float64Array(N), fy = new Float64Array(N), fz = new Float64Array(N);
  var lx = new Float64Array(N), ly = new Float64Array(N), lz = new Float64Array(N);
  var ci = new Int16Array(MAXC), cj = new Int16Array(MAXC), cnx = new Float64Array(MAXC), cny = new Float64Array(MAXC), cnz = new Float64Array(MAXC);
  var cB = new Float64Array(MAXC), cInv = new Float64Array(MAXC), cLam = new Float64Array(MAXC);
  // the kinematic pointer sphere starts at the centre, as in the original, until the pointer first moves
  var ptr = [0, 0, 0], hasPointer = false, simTime = 0, lightAngle = 0;

  var SCHEMES = {
    enrichr: ["#e6ff55", "#1a7a4c", "#fbf8f1", "#4b1a9a"],
    indigo: ["#6366f1", "#ec4899", "#38bdf8", "#10b981"],
    amber: ["#f59e0b", "#ef4444", "#8b5cf6", "#06b6d4"],
    rose: ["#f43f5e", "#a855f7", "#3b82f6", "#14b8a6"],
    frost: ["#ffffff", "#f43f5e", "#38bdf8", "#a855f7"]
  };
  var ORDER = ["enrichr", "indigo", "amber", "rose", "frost"];
  var NAMES = { enrichr: "Enrichr", indigo: "Indigo and pink", amber: "Amber and violet", rose: "Rose and blue", frost: "White and rose" };
  var LOCAL = [[-8, 6, -5], [8, -6, 2], [0, 8, -8]], POWER = [60, 50, 40];
  var DEF = { scheme: "enrichr", lights: "1", orbit: 0.4, pushStrength: 25, pushRadius: 4.5, glow: 0.65, fog: 0.012, light1: "#fbf8f1", light2: "#e6ff55", light3: "#4b1a9a", background: "#0c1e18" };
  var pal = 0, cur = [], goal = [];
  var bufP = new Float32Array(N * 3), bufC = new Float32Array(12), bufLP = new Float32Array(9), bufLC = new Float32Array(9);

  var VS = "attribute vec2 p;void main(){gl_Position=vec4(p,0.0,1.0);}";
  var FS = [
    "#ifdef GL_FRAGMENT_PRECISION_HIGH", "precision highp float;", "#else", "precision mediump float;", "#endif",
    "uniform vec2 uRes;uniform vec3 uP[18];uniform vec3 uC[4];uniform vec3 uLP[3];uniform vec3 uLC[3];uniform vec3 uBg;",
    "uniform float uGlow;uniform float uFog;uniform float uTan;",
    "const float R=1.1;const float PI=3.141592653589793;const vec3 CAM=vec3(0.0,0.0,35.0);",
    // three.js r128 ACES filmic tone mapping
    "vec3 rrt(vec3 v){vec3 a=v*(v+0.0245786)-0.000090537;vec3 b=v*(0.983729*v+0.4329510)+0.238081;return a/b;}",
    "vec3 aces(vec3 c){mat3 mi=mat3(vec3(0.59719,0.07600,0.02840),vec3(0.35458,0.90834,0.13383),vec3(0.04823,0.01566,0.83777));",
    "mat3 mo=mat3(vec3(1.60475,-0.10208,-0.00327),vec3(-0.53108,1.10813,-0.07276),vec3(-0.07367,-0.00605,1.07602));",
    "c*=1.3/0.6;c=mi*c;c=rrt(c);c=mo*c;return clamp(c,0.0,1.0);}",
    // GGX specular with Schlick fresnel and Smith visibility, as in three.js r128
    "vec3 ggx(vec3 L,vec3 V,vec3 N,vec3 f0,float rough){float a=rough*rough;float a2=a*a;vec3 h=normalize(L+V);",
    "float nl=clamp(dot(N,L),0.0,1.0);float nv=clamp(dot(N,V),0.0,1.0);float nh=clamp(dot(N,h),0.0,1.0);float lh=clamp(dot(L,h),0.0,1.0);",
    "vec3 F=(1.0-f0)*exp2((-5.55473*lh-6.98316)*lh)+f0;",
    "float gv=nl*sqrt(a2+(1.0-a2)*nv*nv);float gl=nv*sqrt(a2+(1.0-a2)*nl*nl);float G=0.5/max(gv+gl,1e-6);",
    "float d=nh*nh*(a2-1.0)+1.0;return F*(G*a2/(PI*d*d));}",
    "vec3 col4(int i){int m=i-(i/4)*4;if(m==0)return uC[0];if(m==1)return uC[1];if(m==2)return uC[2];return uC[3];}",
    // metalness 0.85, roughness 0.15, reflectivity 0.9, clearcoat 1 (roughness 0.1), ambient 1.5, emissive = colour x glow
    "vec3 shade(vec3 P,vec3 N,vec3 base,float gr){vec3 V=normalize(CAM-P);vec3 diff=base*0.15;vec3 spec=mix(vec3(0.1296),base,0.85);",
    "float rs=min(0.15+gr,1.0);float rc=min(0.1+gr,1.0);vec3 col=1.5*diff;",
    "for(int k=0;k<3;k++){vec3 lv=uLP[k]-P;float dist=length(lv);vec3 L=lv/dist;float nl=clamp(dot(N,L),0.0,1.0);",
    "vec3 irr=uLC[k]*(clamp(1.0-dist/60.0,0.0,1.0)*nl*PI);float cc=0.04+0.96*pow(1.0-nl,5.0)*(1.0-rc)*(1.0-rc);",
    "col+=irr*ggx(L,V,N,vec3(0.04),rc);col+=(1.0-cc)*irr*(ggx(L,V,N,spec,rs)+diff/PI);}",
    "col+=base*uGlow;col=aces(col);float z=CAM.z-P.z;return mix(col,uBg,1.0-exp(-uFog*uFog*z*z));}",
    "void main(){vec2 ndc=gl_FragCoord.xy/uRes*2.0-1.0;vec3 rd=normalize(vec3(ndc.x*uTan*uRes.x/uRes.y,ndc.y*uTan,-1.0));",
    "float pk=2.0*uTan/uRes.y;float tb=1e9;int ib=-1;vec3 cb=vec3(0.0);float cov=0.0;",
    "for(int i=0;i<18;i++){vec3 oc=uP[i]-CAM;float b=dot(oc,rd);if(b<=0.0)continue;float d2=max(dot(oc,oc)-b*b,0.0);",
    "float pw=pk*b;float rr=R+0.5*pw;if(d2>rr*rr)continue;float t=b-sqrt(max(R*R-d2,0.0));",
    "if(t<tb){tb=t;ib=i;cb=uP[i];cov=clamp((rr-sqrt(d2))/pw,0.0,1.0);}}",
    "if(ib<0){gl_FragColor=vec4(uBg,1.0);return;}",
    "vec3 P=CAM+rd*tb;vec3 col=shade(P,normalize(P-cb),col4(ib),pk*tb/R);",
    "if(cov<1.0){float t2=1e9;int i2=-1;vec3 c2=vec3(0.0);",
    "for(int i=0;i<18;i++){if(i==ib)continue;vec3 oc=uP[i]-CAM;float b=dot(oc,rd);float d2=dot(oc,oc)-b*b;if(b<=0.0||d2>R*R)continue;",
    "float t=b-sqrt(R*R-d2);if(t<t2){t2=t;i2=i;c2=uP[i];}}",
    "vec3 back=uBg;if(i2>=0){vec3 P2=CAM+rd*t2;back=shade(P2,normalize(P2-c2),col4(i2),pk*t2/R);}col=mix(back,col,cov);}",
    "gl_FragColor=vec4(col,1.0);}"
  ].join("\n");

  function num(v, d) { v = Number(v); return isFinite(v) ? v : d; }
  function rgb(h, d) { var m = /^#?([0-9a-f]{6})$/i.exec(h || ""); var v = parseInt(m ? m[1] : d, 16); return [(v >> 16) / 255, ((v >> 8) & 255) / 255, (v & 255) / 255]; }

  // ---------- physics: a cannon.js-style world with no gravity ----------
  function scatter() {
    for (var i = 0; i < N; i++) {
      px[i] = (Math.random() - 0.5) * 14; py[i] = (Math.random() - 0.5) * 14; pz[i] = (Math.random() - 0.5) * 14;
      vx[i] = vy[i] = vz[i] = 0; fx[i] = fy[i] = fz[i] = 0;
    }
  }
  // one contact: body a (-1 = the pointer sphere, which never moves) against sphere b, normal from a to b
  function contact(k, a, b, ax, ay, az, rsum) {
    var dx = px[b] - ax, dy = py[b] - ay, dz = pz[b] - az, d2 = dx * dx + dy * dy + dz * dz;
    if (d2 >= rsum * rsum) return k;
    var d = Math.sqrt(d2);
    if (d < 1e-9) { dx = 1; dy = 0; dz = 0; d = 1e-9; } else { dx /= d; dy /= d; dz /= d; }
    var ia = a < 0 ? 0 : 1, g = d - rsum;
    var vrel = (vx[b] * dx + vy[b] * dy + vz[b] * dz) - (a < 0 ? 0 : vx[a] * dx + vy[a] * dy + vz[a] * dz);
    var fm = (fx[b] * dx + fy[b] * dy + fz[b] * dz) - (a < 0 ? 0 : fx[a] * dx + fy[a] * dy + fz[a] * dz);
    ci[k] = a; cj[k] = b; cnx[k] = dx; cny[k] = dy; cnz[k] = dz;
    cB[k] = -g * SA - vrel * SB - H * fm; // restitution 0, so (1 + e) = 1
    cInv[k] = 1 / (ia + 1 + SEPS); cLam[k] = 0;
    return k + 1;
  }
  function internalStep() {
    var n = 0, i, j, it, k;
    for (i = 0; i < N; i++) {
      for (j = i + 1; j < N; j++) n = contact(n, i, j, px[i], py[i], pz[i], R * 2);
      n = contact(n, -1, i, ptr[0], ptr[1], ptr[2], R + PR);
    }
    for (i = 0; i < N; i++) lx[i] = ly[i] = lz[i] = 0;
    for (it = 0; it < 10; it++) {
      var tot = 0;
      for (k = 0; k < n; k++) {
        var a = ci[k], b = cj[k], nx = cnx[k], ny = cny[k], nz = cnz[k];
        var gwl = (lx[b] * nx + ly[b] * ny + lz[b] * nz) - (a < 0 ? 0 : lx[a] * nx + ly[a] * ny + lz[a] * nz);
        var dl = cInv[k] * (cB[k] - gwl - SEPS * cLam[k]);
        if (cLam[k] + dl < 0) dl = -cLam[k];
        cLam[k] += dl; tot += dl > 0 ? dl : -dl;
        lx[b] += nx * dl; ly[b] += ny * dl; lz[b] += nz * dl;
        if (a >= 0) { lx[a] -= nx * dl; ly[a] -= ny * dl; lz[a] -= nz * dl; }
      }
      if (tot * tot < 1e-14) break;
    }
    for (i = 0; i < N; i++) {
      vx[i] = (vx[i] + lx[i]) * DAMP; vy[i] = (vy[i] + ly[i]) * DAMP; vz[i] = (vz[i] + lz[i]) * DAMP;
      vx[i] += fx[i] * H; vy[i] += fy[i] * H; vz[i] += fz[i] * H;
      px[i] += vx[i] * H; py[i] += vy[i] * H; pz[i] += vz[i] * H;
      fx[i] = fy[i] = fz[i] = 0;
    }
  }
  // forces are added once a frame, like applyForce in the original's animation loop; k scales them so a 120 Hz screen
  // pushes as hard as a 60 Hz one
  function addForces(k) {
    var R2 = opts.pushRadius, S = opts.pushStrength;
    for (var i = 0; i < N; i++) {
      var x = px[i], y = py[i], z = pz[i];
      if (x * x + y * y + z * z > 30) { fx[i] -= x * 0.6 * k; fy[i] -= y * 0.6 * k; fz[i] -= z * 0.6 * k; }
      if (hasPointer) {
        var dx = x - ptr[0], dy = y - ptr[1], dz = z - ptr[2], d = Math.sqrt(dx * dx + dy * dy + dz * dz);
        if (d < R2 && d > 0.001) { var f = (1 - d / R2) * S * k / d; fx[i] += dx * f; fy[i] += dy * f; fz[i] += dz * f; }
      }
    }
  }
  // world.step(1/60, delta, 3): as many fixed steps as the clock has crossed, at most three
  function stepWorld(delta) {
    var steps = Math.min(3, Math.floor((simTime + delta) / H) - Math.floor(simTime / H));
    for (var s = 0; s < steps; s++) internalStep();
    simTime += delta;
  }
  function settle(frames) { for (var s = 0; s < frames; s++) { internalStep(); addForces(1); } }

  // ---------- colours ----------
  function setScheme(idx, snap) {
    pal = ((idx % ORDER.length) + ORDER.length) % ORDER.length;
    var list = SCHEMES[ORDER[pal]];
    for (var k = 0; k < 4; k++) { goal[k] = rgb(list[k], "e6ff55"); if (snap || !cur[k]) cur[k] = goal[k].slice(); }
  }
  function easeColours(delta) {
    var t = 1 - Math.pow(0.9, delta * 60); // lerp(target, 0.1) every frame at 60 fps
    for (var k = 0; k < 4; k++) for (var c = 0; c < 3; c++) cur[k][c] += (goal[k][c] - cur[k][c]) * t;
  }

  // ---------- WebGL ----------
  function sh(type, src) { var s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s); return gl.getShaderParameter(s, gl.COMPILE_STATUS) ? s : null; }
  function setup() {
    var v = sh(gl.VERTEX_SHADER, VS), f = sh(gl.FRAGMENT_SHADER, FS);
    if (!v || !f) return false;
    prog = gl.createProgram(); gl.attachShader(prog, v); gl.attachShader(prog, f); gl.linkProgram(prog);
    gl.deleteShader(v); gl.deleteShader(f);
    if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) return false;
    gl.useProgram(prog);
    vb = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vb);
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);
    var loc = gl.getAttribLocation(prog, "p"); gl.enableVertexAttribArray(loc); gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0);
    ["uRes", "uP", "uC", "uLP", "uLC", "uBg", "uGlow", "uFog", "uTan"].forEach(function (k) { u[k] = gl.getUniformLocation(prog, k); });
    return true;
  }
  function size() {
    var dpr = Math.min(window.devicePixelRatio || 1, 2);
    var w = Math.max(1, Math.round(wrap.clientWidth * dpr)), h = Math.max(1, Math.round(wrap.clientHeight * dpr));
    if (canvas.width !== w || canvas.height !== h) { canvas.width = w; canvas.height = h; gl.viewport(0, 0, w, h); }
  }
  function draw() {
    if (!ok || destroyed || gl.isContextLost()) return;
    size();
    var i, k;
    for (i = 0; i < N; i++) { bufP[i * 3] = px[i]; bufP[i * 3 + 1] = py[i]; bufP[i * 3 + 2] = pz[i]; }
    for (k = 0; k < 4; k++) { bufC[k * 3] = cur[k][0]; bufC[k * 3 + 1] = cur[k][1]; bufC[k * 3 + 2] = cur[k][2]; }
    // the light group: tilted -45 degrees about x, turning about its own y axis (three.js Euler order XYZ)
    var ca = Math.cos(lightAngle), sa = Math.sin(lightAngle), cx = Math.cos(-Math.PI / 4), sx = Math.sin(-Math.PI / 4);
    var on = opts.lights !== "0" && opts.lights !== 0 && opts.lights !== false;
    var cols = [rgb(opts.light1, "fbf8f1"), rgb(opts.light2, "e6ff55"), rgb(opts.light3, "4b1a9a")];
    for (k = 0; k < 3; k++) {
      var L = LOCAL[k], x1 = ca * L[0] + sa * L[2], y1 = L[1], z1 = -sa * L[0] + ca * L[2];
      bufLP[k * 3] = x1; bufLP[k * 3 + 1] = cx * y1 - sx * z1; bufLP[k * 3 + 2] = sx * y1 + cx * z1;
      for (var c = 0; c < 3; c++) bufLC[k * 3 + c] = on ? cols[k][c] * POWER[k] : 0;
    }
    gl.uniform2f(u.uRes, canvas.width, canvas.height);
    gl.uniform3fv(u.uP, bufP); gl.uniform3fv(u.uC, bufC);
    gl.uniform3fv(u.uLP, bufLP); gl.uniform3fv(u.uLC, bufLC);
    gl.uniform3fv(u.uBg, rgb(opts.background, "0c1e18"));
    gl.uniform1f(u.uGlow, opts.glow); gl.uniform1f(u.uFog, opts.fog); gl.uniform1f(u.uTan, TANH);
    gl.drawArrays(gl.TRIANGLES, 0, 3);
  }

  function loop(now) {
    raf = requestAnimationFrame(loop);
    var delta = Math.min(0.1, Math.max(0, (now - last) / 1000)); last = now;
    if (!visible || document.hidden) return;
    stepWorld(delta);
    lightAngle += delta * opts.orbit;
    addForces(delta * 60);
    easeColours(delta);
    draw();
  }

  // ---------- input ----------
  function onMove(e) {
    var r = wrap.getBoundingClientRect();
    if (!r.width || !r.height) return;
    var nx = (e.clientX - r.left) / r.width * 2 - 1, ny = -((e.clientY - r.top) / r.height) * 2 + 1;
    // the ray from the camera meets the z = 0 plane at a distance of 35
    ptr[0] = CAMZ * nx * TANH * (r.width / r.height); ptr[1] = CAMZ * ny * TANH; ptr[2] = 0;
    hasPointer = true;
  }
  function onLeave() { hasPointer = false; ptr[0] = ptr[1] = ptr[2] = -100; }
  function cycle() {
    setScheme(pal + 1, reduce);
    if (live) live.textContent = "Palette: " + NAMES[ORDER[pal]];
    if (reduce) draw();
  }
  function onLost(e) { e.preventDefault(); canvas.style.display = "none"; if (btn) btn.hidden = true; }

  function update(partial) {
    partial = partial || {};
    opts = Object.assign({}, DEF, opts, partial);
    ["orbit", "pushStrength", "pushRadius", "glow", "fog"].forEach(function (k) { opts[k] = Math.max(0, num(opts[k], DEF[k])); });
    opts.pushRadius = Math.max(0.1, opts.pushRadius);
    if (!cur.length || "scheme" in partial) { var i = ORDER.indexOf(String(opts.scheme)); setScheme(i < 0 ? 0 : i, reduce || !cur.length); }
    wrap.style.setProperty("--ef-orbs-bg", opts.background);
    if (destroyed) return;
    draw();
  }

  scatter();
  try { gl = canvas.getContext("webgl", { antialias: false, alpha: false, powerPreference: "high-performance" }); } catch (e) { gl = null; }
  ok = !!gl && setup();
  if (!ok) { canvas.style.display = "none"; if (btn) btn.hidden = true; }
  else canvas.addEventListener("webglcontextlost", onLost);
  if (reduce) { opts = Object.assign({}, DEF, o || {}); settle(300); lightAngle = 1.2; }
  update(o);
  if (ok) {
    wrap.addEventListener("click", cycle);
    if (!reduce) {
      wrap.addEventListener("pointermove", onMove);
      wrap.addEventListener("pointerleave", onLeave);
      if ("IntersectionObserver" in window) { io = new IntersectionObserver(function (e) { visible = e[0].isIntersecting; }); io.observe(wrap); }
      last = performance.now(); raf = requestAnimationFrame(loop);
    }
    if ("ResizeObserver" in window) { ro = new ResizeObserver(function () { if (!destroyed) draw(); }); ro.observe(wrap); }
  }
  return {
    update: update,
    destroy: function () {
      destroyed = true; cancelAnimationFrame(raf);
      wrap.removeEventListener("click", cycle);
      wrap.removeEventListener("pointermove", onMove);
      wrap.removeEventListener("pointerleave", onLeave);
      canvas.removeEventListener("webglcontextlost", onLost);
      if (io) io.disconnect();
      if (ro) ro.disconnect();
      if (gl) {
        var ext = gl.getExtension("WEBGL_lose_context");
        if (vb) gl.deleteBuffer(vb); if (prog) gl.deleteProgram(prog);
        if (ext) ext.loseContext();
        gl = null;
      }
    }
  };
}

// Usage
var fx = mount(document.querySelector("#my-root"), {"scheme":"enrichr","lights":1,"orbit":0.4,"pushStrength":25,"pushRadius":4.5,"glow":0.65,"fog":0.012,"light1":"#fbf8f1","light2":"#e6ff55","light3":"#4b1a9a","background":"#0c1e18"});

How it works

The physics is a small solver written to match cannon.js as the original pen used it: no gravity, fixed steps of 1/60 of a second (up to three a frame), linear damping of 0.35, and sphere contacts solved like cannon's default contact (Spook stiffness 10 million, relaxation 3, no bounce, ten Gauss-Seidel passes). Every frame each sphere further than the square root of 30 from the centre is pulled back with a force of -0.6 times its position, and each sphere within the push radius of the pointer is pushed away with (1 - distance / radius) times the strength. The pointer is also a 1.5-unit sphere the balls collide with; its position is where the camera ray meets the z = 0 plane. The picture is one fragment shader: for each pixel it intersects the ray with all 18 spheres and keeps the nearest, smoothing the silhouette over one pixel. It shades the hit like the original MeshPhysicalMaterial (metalness 0.85, roughness 0.15, clearcoat 1, emissive glow) under three point lights on a ring tilted 45 degrees, then applies ACES filmic tone mapping at exposure 1.3 and exponential fog towards the background. A palette change eases each colour 10% of the way every frame.

Accessibility and performance

The canvas has a text label. The Change palette button does the same as a click on the scene, works with Enter and Space, and the new palette name is announced through a polite live region. With prefers-reduced-motion the spheres settle first and one still frame is drawn; the button still changes the palette instantly. Nothing flashes.

The physics is about 170 pair checks a step, so it costs almost nothing. The shader tests 18 spheres per pixel and shades one (two on silhouette edges), which is light on any graphics card but is the heaviest part, so the pixel ratio is capped at 2, the loop pauses off screen and in hidden tabs, and destroy() frees the WebGL context. Without WebGL the CSS background stays and the button is hidden.

SectionBackground
TechniquesWebGL, Pointer interaction
StackVanilla JS, WebGL
Works withReact, Next.js, Vanilla
DependenciesNone
Statustested
On CodePenOpen the live pen on our CodePen account; fork it to experiment.
Inspired byInteractive 3D Physics Spheres with SSGI by Enrichr on CodePen. Original code, written from scratch.

Find this technique on a real site

Want to see this technique in the wild? Check any site with the free tools, then build your own version from this page.

Check which animation library a site uses · Extract a site's design tokens · Browse site breakdowns

Licence and provenance

Free to use in personal and client projects during the preview. Final licence terms will be published here before any paid tier starts; ask before reselling the code as a collection.

This is original code. The technique is a common one that we studied by measuring award-winning sites with Enrichr; no third-party code, shaders, fonts or images are used.

Depth map shaderA photo and its depth map drawn by a WebGL shader, so the near parts of the picture move more than the far ones as the pointer moves. Wave image WebGLA generated artwork on a raw WebGL mesh that ripples with sine waves and swells where the pointer moves. Glass torus heroA glossy glass torus knot turns slowly in front of a huge three-line headline, bending the letters and splitting their edges into colour.

FAQ

Does it need three.js or cannon.js?

No. The spheres are ray-traced analytically in one fragment shader and the physics is a short sphere solver that copies cannon.js's contact, damping and stepping rules, so the motion matches the original.

Why do the spheres look soft and slightly misty?

That is the original's look: exponential fog of 0.025 at a camera distance of 35 mixes about half of the background colour into every sphere after tone mapping. Lower the fog density for brighter, crisper spheres.

Why is there a gap in the middle before I move the pointer?

The original adds the pointer as a 1.5-unit collision sphere at the centre before the pointer first moves, and that is kept. Once you move the pointer it follows you, and leaving the box parks it far away.

Can I use my own colours?

Each palette has four colours, used in turn across the 18 spheres. Pick a palette from the list, then set the three light colours and the background. To add a palette, add a line to SCHEMES in element.js.