Three.js From Zero · Article s16-04

Fourier Epicycles — Drawing With a Machine Made of Circles

A hand-written DFT turns any shape into a chain of spinning circles that redraws it — with a terms slider that doubles as a live compression demo. Part of the MasterAllArts Creative 3D Roadmap.

Part of the MasterAllArts Creative 3D Roadmap .

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

Season 16 · Article 04 · Beautiful Math

Take any closed shape. The discrete Fourier transform converts it into a list of circles — each with a size, a spin speed, and a starting angle. Chain them tip-to-tail, let them spin, and the end of the chain redraws your shape. Exactly. This is the most-watched piece of math animation on the internet, and the entire engine fits in twelve lines.

— fps · — terms

Drag to orbit — the machine is flat but lives in a 3D scene, and a low side angle makes the circle chain read like clockwork. Now do the experiment: drag terms down to 4 and the heart melts into a wobbling potato. Push it to 16 — recognizably a heart. At 64, the lobes sharpen. Every term you add is one more circle in the chain and one more octave of detail. You are scrubbing through a Fourier series with your thumb.

One sentence of theory

Treat each point of your shape as a complex number (x + iy). The discrete Fourier transform rewrites the sequence of N points as a sum of N rotating vectors — frequency k spins k times per lap, its coefficient ck says how long the vector is and where it starts:

c_k = (1/N) · Σₙ  p_n · e^(−2πi·k·n/N)        // one complex number per frequency

That's it. No approximation — with all N terms the sum passes through every input point. An "epicycle machine" is just this sum evaluated visually: each rotating vector becomes a circle of radius |ck| spinning at frequency k, mounted on the tip of the previous one.

Step 1 — The DFT in twelve lines

No library. For the few hundred points a drawing needs, the naive O(N²) transform runs in a millisecond, and writing it yourself is the entire point of this season:

function dft(points) {                       // points: [{x, y}, ...]
  const N = points.length, coeffs = [];
  for (let k = -N / 2; k < N / 2; k++) {     // signed frequencies: spin both ways
    let re = 0, im = 0;
    for (let n = 0; n < N; n++) {
      const phi = (-2 * Math.PI * k * n) / N;
      re += points[n].x * Math.cos(phi) - points[n].y * Math.sin(phi);
      im += points[n].x * Math.sin(phi) + points[n].y * Math.cos(phi);
    }
    re /= N; im /= N;
    coeffs.push({ freq: k, amp: Math.hypot(re, im), phase: Math.atan2(im, re) });
  }
  return coeffs.sort((a, b) => b.amp - a.amp);   // big circles first
}

Two decisions in there matter visually. Signed frequencies: circles must be allowed to spin both directions, or half your shapes are unreachable. And the sort by amplitude: it puts the huge, slow circles at the base of the chain and the tiny, fast ones at the pen — which is what makes the machine legible, and what makes the terms slider work as a detail knob.

Step 2 — Build the machine from one geometry

Up to 128 circles on screen, but only one circle geometry in memory — a unit LineLoop that every epicycle shares, scaled and positioned per frame. Same one-geometry-many-objects move as the spine/halo pair in the harmonograph, pushed further:

const ring = new THREE.BufferGeometry().setFromPoints(
  Array.from({ length: 65 }, (_, i) => {
    const a = (i / 64) * Math.PI * 2;
    return new THREE.Vector3(Math.cos(a), Math.sin(a), 0);
  }),
);
const circles = Array.from({ length: MAX_TERMS }, () =>
  new THREE.LineLoop(ring, circleMaterial));   // shared geometry AND material
circles.forEach((c) => scene.add(c));

Per frame, walk the coefficient list and accumulate the chain — each circle sits at the running sum before its own term is added:

let x = 0, y = 0;
for (let i = 0; i < terms; i++) {
  const { freq, amp, phase } = coeffs[i];
  circles[i].position.set(x, y, 0);
  circles[i].scale.setScalar(amp);
  const a = freq * theta + phase;
  x += amp * Math.cos(a);
  y += amp * Math.sin(a);
}
// (x, y) is now the pen

No matrices to compose by hand, no geometry rebuilt — moving a LineLoop is just setting position and scale. The GPU never hears about any of it until the draw.

Pitfall: don't rebuild what you can re-pose. The reflex from 2D canvas is to regenerate the circle's vertices every frame at the new radius. In a scene graph that's backwards: geometry is the expensive, GPU-resident thing; transforms are four floats. If an object only moves, rotates, or scales — re-pose it. Rebuild geometry only when the shape of the data changes (here: only when you pick a new target drawing).

Step 3 — The trail is a ring buffer indexed by phase

The pen retraces the same closed path every lap, so the trail buffer doesn't need to grow forever — it needs exactly one lap of slots. Map the machine's angle θ to a buffer index and write the pen position there:

const slot = Math.floor((theta % TAU) / TAU * TRAIL_N);
trailPos[slot * 3 + 0] = x;
trailPos[slot * 3 + 1] = y;
trailPos[slot * 3 + 2] = 0;
trailAttr.needsUpdate = true;

First lap, the shape draws itself in; after that, the machine continuously re-writes the same slots — so when you move the terms slider mid-spin, the trail morphs into the new approximation within one lap, no reset needed. Recency still gets a color: each frame, tint every slot by its angular distance behind the pen — bright at the head, cooling toward the tail. A 1,024-slot color rewrite per frame is nothing.

Step 4 — The terms slider is a compression demo

Because coefficients are sorted by amplitude, drawing the top T terms is optimal lossy compression of the shape — literally the same idea as JPEG keeping the big frequency components and discarding the small ones. The heart at 16 of 256 terms is 94% recognizable at 6% of the data. When a client asks why their logo SVG can be "simplified," this slider is the explanation.

What the controls teach

  • shape — four parametric curves, resampled to 256 points and re-DFT'd on the spot. The butterfly (Fay's curve, 1989) needs the most terms — count how many before the wing notches appear.
  • terms — the Fourier series partial sum, live. Watch which circles vanish as you drop terms: always the smallest, fastest ones at the pen end.
  • speed — clockwork pacing. Slow it to 0.25 to watch individual circles hand off motion to each other.
  • circles — hide the machine, keep the drawing. The difference between watching math and watching magic.

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';

// sample shape → dft() → coeffs sorted by amplitude     (Step 1)
// MAX_TERMS LineLoops sharing one unit-ring geometry    (Step 2)
// per frame: accumulate chain, re-pose circles,
//            write pen into phase-indexed trail slot    (Step 3)
</script>