Three.js From Zero · Article s16-03

Harmonograph — A Victorian Drawing Machine in WebGL

Damped pendulums draw glowing 3D Lissajous webs: closed-form curve sampling, one geometry drawn twice for cheap glow, and a setDrawRange pen reveal. Part of the MasterAllArts Creative 3D Roadmap.

Part of the MasterAllArts Creative 3D Roadmap .

← Three.js From Zero S16-03 · Beautiful Math

Season 16 · Article 03 · Beautiful Math

In the 1840s you'd build this out of brass and lead: two pendulums swing a pen over a table, a third sways the table itself, friction slowly bleeds the energy out, and the decaying orbit writes itself onto paper as a spiraling web. We get to skip the brass. Four sine waves and an exponential decay, sampled into one buffer — then drawn by a glowing pen, in 3D, sixty times a second.

— fps · — / — points

Drag to orbit while it draws. Every slider restarts the pen. The fastest route to a gasp is surprise me — but the educated route is setting fx and fy to a simple ratio (try fx 2.00, fy 3.00), watching the clean Lissajous knot, then nudging fy to 3.01 and watching that knot slowly precess into a woven basket. A hundredth of a hertz is the difference between geometry and lace.

The math: four sines and a leak

A harmonograph is just simple harmonic motion with friction. Each axis is a damped sinusoid — and because real pendulums never swing in one pure mode, the classic recipe adds a quieter, slightly-detuned partner on each axis. From my old 2D atlas sketch, per axis:

x(t) = e^(-d·t)      · sin(fx·t + φ) · A₁     // main pendulum
     + e^(-0.7·d·t)  · sin((fx+0.7)·t) · A₂    // its quieter overtone

The exponential is the soul of the machine. Without it you have a Lissajous figure — a closed loop, elegant and dead. The decay makes every orbit slightly smaller than the last, so the curve never crosses itself the same way twice and the figure gains depth on paper. In 3D we give the z-axis its own pendulum (the Victorian version swayed the table), and the decay gains literal depth.

Note what kind of object this is, because it's the opposite of the Lorenz attractor: a closed-form curve. Lorenz must be integrated step by step — you can't know where a particle will be at t=40 without simulating everything before it. The harmonograph hands you x(t) directly for any t. Closed form means you can sample it all at once, in any order, at any resolution. Different math, different rendering strategy.

Step 1 — Sample the whole curve into one buffer

Since we can evaluate any t instantly, we precompute the entire drawing the moment a slider moves — 24,000 vertices, positions and colors, one pass:

const N = 24000;
const T_MAX = Math.min(3 / decay, 600);   // run until ~95% of the energy is gone

for (let i = 0; i < N; i++) {
  const t = (i / N) * T_MAX;
  positions[i * 3 + 0] = xAxis(t);   // damped sin + overtone
  positions[i * 3 + 1] = yAxis(t);
  positions[i * 3 + 2] = zAxis(t);
}
geometry.getAttribute('position').needsUpdate = true;

T_MAX = 3/decay is worth a pause: e^(−d·t) hits 5% at t ≈ 3/d, so the duration adapts to the slider. Heavy damping → short, tight spiral; light damping → long, airy web. The buffer size never changes; only the time window it covers does. Allocate once, rewrite forever — the same discipline as the Lorenz particle buffers.

Step 2 — One geometry, two draws

A 1-pixel THREE.Line through 24,000 points already looks good with additive blending. But the trick that makes it look lit from within costs two lines of code: add a THREE.Points object sharing the same geometry, with soft, low-opacity dots. The line gives the curve a crisp spine; the points smear a faint halo around it. Two draw calls, zero extra memory:

const geometry = new THREE.BufferGeometry();
geometry.setAttribute('position', posAttr);
geometry.setAttribute('color', colAttr);

const spine = new THREE.Line(geometry, new THREE.LineBasicMaterial({
  vertexColors: true, blending: THREE.AdditiveBlending,
  transparent: true, opacity: 0.9, depthWrite: false,
}));
const halo = new THREE.Points(geometry, new THREE.PointsMaterial({
  vertexColors: true, blending: THREE.AdditiveBlending,
  transparent: true, opacity: 0.22, size: 0.5, sizeAttenuation: true,
  depthWrite: false,
}));
scene.add(spine, halo);

Sharing one BufferGeometry between multiple objects is fully supported and criminally underused. Update the attribute once, every consumer sees it — including, in a moment, the draw range.

Pitfall: linewidth is a lie. LineBasicMaterial accepts a linewidth property and then almost every platform ignores it — WebGL core only guarantees 1px lines. If you need genuinely thick strokes, the upgrade paths are Line2 / LineMaterial from the addons (screen-space quads) or TubeGeometry (real 3D thickness). For glowing math curves, the line+points halo above is cheaper than both and usually looks better.

Step 3 — Let the machine draw

Showing the finished figure wastes the best part — a harmonograph is a performance. The reveal is setDrawRange: tell the GPU to draw only the first k vertices, and animate k. It's the line-geometry cousin of the mesh.count trick from the phyllotaxis article — same idea, same price: free.

// in the render loop, while drawing:
const progress = Math.min(1, (now - drawStart) / 9000);
const k = Math.max(2, Math.floor(progress * N));
geometry.setDrawRange(0, k);              // spine AND halo obey — shared geometry
pen.position.fromBufferAttribute(posAttr, k - 1);   // glowing pen at the tip
pen.visible = progress < 1;

The pen is a small white sphere riding the last drawn vertex — fromBufferAttribute reads its position straight out of the buffer, no recomputation. Because vertices are spaced evenly in time, the pen automatically moves fast through the early wide orbits and slows as the energy drains. The physics is in the spacing; the animation inherits it for free.

Step 4 — Color is time

Season pattern, third appearance: find the system's own scalar and feed it a lerp. For Lorenz it was speed; for phyllotaxis, seed age; here it's elapsed time — which, thanks to the decay, doubles as energy:

c.copy(hotStart).lerp(coolEnd, i / N);    // early/energetic → late/settled
colors[i * 3 + 0] = c.r; colors[i * 3 + 1] = c.g; colors[i * 3 + 2] = c.b;

The outer violent loops burn orange, the dying center cools to blue-violet, and the eye reads the whole history of the pendulum at a glance.

What the sliders teach

  • fx : fy ratio — small integers (2:3, 3:4) give recognizable Lissajous knots. The phase slider rotates which knot you get.
  • detuning — set a clean ratio, then move one frequency by 0.01. The figure precesses one notch per orbit: that slow rotation is the beat frequency between the two pendulums, made visible.
  • decay — the artist's knob. Low decay draws an airy wireframe vessel; high decay a dense scribble collapsing to the center. Notice the drawing duration change with it (that's T_MAX = 3/d adapting).
  • fz — pure 3D drama: it controls how the figure breathes along the camera axis. Set it near fx for a tilted ribbon, far for a tumbling cage.

The skeleton

<script type="importmap">
{ "imports": {
    "three": "https://unpkg.com/three@0.170.0/build/three.module.js",
    "three/addons/": "https://unpkg.com/three@0.170.0/examples/jsm/" } }
</script>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

// scene / camera / renderer / controls
// allocate N-vertex position+color buffers once         (Step 1)
// Line (spine) + Points (halo) share the geometry       (Step 2)
// render loop: setDrawRange reveal + pen sphere         (Step 3)
</script>