Creative Coding From Zero · Episode 05

Trigonometry & Cycles

Trigonometry & Cycles is Episode 05 of Creative Coding From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.

Part of the MasterAllArts Creative 3D Roadmap .

Episode 05 · Creative Coding From Zero

Every smooth motion you have ever seen is a sine wave wearing a costume. A planet sweeping its orbit, a pendulum easing back and forth, the green spike of a heartbeat monitor, a bobbing buoy, the breathing glow of a sleep light — none of them move in straight lines and none of them snap. They ease. And the thing that eases, underneath, is always the same: a point going around a circle, watched from the side. That is what sin and cos are. Not triangles. Not homework. A position on a spinning wheel.

Once you see trig as "go around a circle and read off the shadow," you can build motion that feels alive instead of mechanical — and you can chain circles onto circles to draw curves that look hand-spun on a machine from 1965. This episode is a spirograph and harmonograph studio: feed it two frequencies, a phase, and a touch of damping, and it traces mesmerizing closed curves — rosettes, knots, spirals that wind inward forever. Hit regenerate and it hands you a brand-new one, deterministically, from a single seed. Steal the screenshots.

0 fps
canvas 2D · parametric
A single point orbits a circle. x = cos(t), y = sin(t). This is the engine.

What you're looking at

One system, six views, and a fixed set of dials. The stage selector walks you from the bare unit circle up to a finished multi-curve composition. freq A and freq B are the two integers that decide how many times each axis oscillates per loop — their ratio is the whole personality of the figure. phase slides one wave against the other (watch a Lissajous bloom from a line into an ellipse into a figure-eight). damping bleeds energy out over time, which is what turns a forever-buzzing curve into a pendulum spiraling to rest. regenerate reseeds the palette and the small per-stage flourishes; PNG saves whatever is on screen. Everything animates the instant the page loads — no input required.

The numbers are deliberately small and the canvas is deliberately dark, because trig art lives on contrast: a thin bright line on black, traced over thousands of sub-steps so the curve reads as a single smooth filament rather than a connect-the-dots polygon. Let's build it one idea at a time.

Stage 1 — A point orbiting (the circle is the engine)

Start with the only fact you need: a point on a circle of radius r, centered at (cx, cy), at angle t, sits at x = cx + cos(t)·r and y = cy + sin(t)·r. Increase t a little every frame and the point sweeps around. That's it. That is a planet's orbit, a clock hand, a record on a turntable. cos is the horizontal shadow of that spinning point; sin is the vertical shadow. The demo draws the circle, the radius arm, and the point — and drops two faint lines onto the axes so you can literally watch cos(t) and sin(t) being read off as the point goes around.

The single most common beginner trap is hiding right here: t is in radians, not degrees. A full turn is 2π ≈ 6.283, not 360. JavaScript's Math.sin/Math.cos only speak radians. Feed them degrees and your "orbit" crawls around roughly six times too fast and nothing lines up.

Stage 2 — A sine wave (the same motion, unrolled)

Now take that orbiting point and ask a different question: as it goes around, how does its height change over time? Plot y = sin(t) with t marching left to right and you get the wave — the gentle up-and-down that is the signature of every cycle. The demo shows both at once: the little orbiter on the left, and to its right the trail its sin value paints as time scrolls. They are the same number. The wave is just the circle unrolled along a time axis. Slow motion in, slow motion out, smoothly through zero — that S-curve through the middle is why sin is the secret behind "ease-in-out" in every animation tool on earth.

This is the mental bridge for the whole episode: circle ↔ wave. When you want something to cycle — pulse, bob, breathe, sway — you reach for sin(t). When you want it to travel a ring, you reach for the cos/sin pair together. They're two faces of one rotation.

Stage 3 — Lissajous (one wave per axis)

Here's the first piece of real magic, and it's almost insultingly simple. Drive x with one sine and y with another, at different frequencies: x = sin(a·t), y = sin(b·t + φ). As t runs, the point can't just go in a circle anymore — it has to satisfy both rhythms at once, and the path it's forced into is a Lissajous figure. Set freq A and freq B equal and you get an ellipse (a tilted line when the phase is zero, a circle when it's a quarter turn). Set them to 3 and 2 and you get a pretzel. The ratio a:b is everything.

And now the pitfall that is secretly the most beautiful idea in the episode: rational ratios close, irrational ratios never do. When a:b is a clean fraction like 3:2, the figure repeats exactly after one period and you get a crisp closed loop. If the ratio were irrational (say a/b = √2), the curve would never rejoin its own start — it would keep filling the box with new line forever, denser and denser. Our sliders are integers so everything closes, but that "never closes" case is the seed of the dense, woven look you'll see in the harmonograph.

Stage 4 — Spirograph (circles riding on circles)

Remember that a point on a circle is (cos t, sin t). What if the center of that circle is itself a point on a bigger, slower circle? You get an epicycle — a wheel rolling around a wheel — and the traced path is a spirograph rosette, all loops and petals. Stack three or four of them, each smaller and spinning faster, and you can draw astonishingly intricate flower-like curves. (This is not a toy fact: a sum of rotating circles is a Fourier series, and with enough terms it can trace literally any closed curve — that's how those "draw any shape with epicycles" animations work.)

The code is a loop that just keeps adding rotating terms onto a running (x, y). Each term has its own radius and its own integer frequency; the freq-A and freq-B sliders feed the inner wheels, so dragging them re-shapes the rosette live. Because all the frequencies are whole numbers, the whole thing closes into a clean repeating bloom.

Stage 5 — Harmonograph (sines that run out of breath)

A real Victorian harmonograph is two or three pendulums dragging a pen across paper. Pendulums swing as sines — but they also lose energy to friction, so each swing is a hair smaller than the last. We model that by multiplying every sine by a decaying envelope: exp(-decay·t)·sin(f·t + φ). Sum a couple of those on each axis and the pen traces a path that spirals gracefully inward, the loops shrinking until the whole thing settles to a dot in the center. It's the most hypnotic curve in the studio, and it's the reason the damping slider exists.

Two failure modes live in this one slider. Set damping to zero and the pendulum never tires — the curve retraces the same loops endlessly and never "settles" into the spiral look that makes a harmonograph a harmonograph. Set it too high and the pen dies almost instantly, drawing a sad little comma. The sweet spot is a gentle bleed, and that's where the default sits.

Stage 6 — Composition (overlay, offset, color)

Everything above was one curve. A piece is several. The final stage layers a handful of harmonograph curves on top of each other, each nudged by a different phase offset and painted from a cosine palette, so the strokes weave through one another into something that looks composed rather than computed. The seed drives the palette and the per-layer offsets, so every regenerate is a genuinely new artwork that you could nonetheless reproduce exactly from its seed number — the whole point of generative art.

That's the arc: a point on a circle (Stage 1) becomes a wave (2), two waves become a figure (3), circles-on-circles become a rosette (4), tired sines become a spiral (5), and a stack of spirals becomes a picture (6). Same three functions the entire way down.

How the code works

(a) The parametric point. The atom of everything. Pick an angle, take its cosine and sine, scale by a radius, offset to a center. Advance the angle to animate. Note cos feeds x and sin feeds y; swap them and you just start the rotation a quarter-turn earlier:

// One point on a circle of radius r, centered at (cx, cy).
function orbit(t, cx, cy, r) {
  const x = cx + Math.cos(t) * r;   // horizontal shadow of the spin
  const y = cy + Math.sin(t) * r;   // vertical shadow of the spin
  return { x, y };
}
// t is RADIANS. A full turn is 2*Math.PI, not 360.

(b) Lissajous x(t), y(t). Two independent sines, one per axis. The frequencies a and b are integers so the figure closes; the phase φ on one of them is what morphs a line into an ellipse into a knot. We sample t in many small steps and connect them with lineTo:

// Trace a closed Lissajous figure: x = sin(a t), y = sin(b t + phase).
ctx.beginPath();
const STEPS = 2000;                 // enough sub-steps = smooth, not polygonal
for (let i = 0; i <= STEPS; i++) {
  const t = (i / STEPS) * Math.PI * 2;   // one full period, 0 → 2π
  const x = cx + Math.sin(a * t)         * R;
  const y = cy + Math.sin(b * t + phase) * R;
  i ? ctx.lineTo(x, y) : ctx.moveTo(x, y);
}
ctx.stroke();

(c) The epicycle sum. A spirograph is just circles added onto circles. Keep a running (x, y) and, for each wheel, add its own rotating contribution. More terms, more detail — this loop is a Fourier series:

// Sum of rotating circles → spirograph rosette.
// wheels = [{ r, freq, phase }, ...]; integer freqs keep it closed.
function epicycle(t, wheels) {
  let x = 0, y = 0;
  for (const w of wheels) {
    x += Math.cos(w.freq * t + w.phase) * w.r;
    y += Math.sin(w.freq * t + w.phase) * w.r;
  }
  return { x, y };
}

(d) The damped harmonograph + tracing the path. Each axis is a sum of sines, but every sine is wrapped in a decaying envelope exp(-decay·t) so the motion winds down. We march t forward and lineTo each sample. Crucially, the curve is traced over a long t range with many steps — that's what produces the inward spiral instead of a jagged scribble:

// Damped harmonograph: two tired pendulums per axis.
function harmono(t, p) {
  const dx = Math.exp(-p.decay * t);   // envelope: energy bleeding away
  const dy = Math.exp(-p.decay * t);
  const x = dx * (Math.sin(p.ax * t + p.px) + 0.5 * Math.sin(p.ax2 * t));
  const y = dy * (Math.sin(p.ay * t + p.py) + 0.5 * Math.sin(p.ay2 * t));
  return { x, y };
}

// Trace it. decay > 0 or it never settles into the spiral.
ctx.beginPath();
for (let i = 0; i <= 6000; i++) {
  const t = i * 0.02;
  const { x, y } = harmono(t, params);
  const px = cx + x * R, py = cy + y * R;
  i ? ctx.lineTo(px, py) : ctx.moveTo(px, py);
}
ctx.stroke();

For the live stages the same idea runs, but the t range that gets drawn grows a little each frame, so you watch the pen draw itself and then loop. The seeded mulberry32 RNG picks the palette and the small per-layer offsets, so a seed reproduces the exact piece — change the seed with regenerate.

Common pitfalls

  • Degrees vs radians. Math.sin and Math.cos take radians. A full turn is 2π. If you paste a value in degrees, multiply by Math.PI / 180 first — otherwise everything spins absurdly fast and no figure ever closes.
  • Aliasing / polygonal curves. A smooth curve drawn with too few t-steps looks like a jagged polygon, especially at high frequencies. Use enough sub-steps (a couple thousand for a closed figure, more for busy ones). When in doubt, scale your step count with the frequencies.
  • Rational vs irrational ratios. Integer (rational) frequency ratios produce closed, repeating figures; irrational ratios produce dense curves that never close. Both are useful — just know which you asked for, or your "closed" figure will quietly keep redrawing slightly-shifted copies forever.
  • A harmonograph with no damping. Without an exp(-decay·t) envelope, the pendulums never tire and the curve never spirals inward — you just get a Lissajous-ish loop retraced endlessly. Damping is the feature, not a bug to remove.
  • Persistence vs clear. To trace a growing path, either redraw the whole path each frame, or never clear and keep extending it. If you clearRect every frame and only draw the newest segment, you'll see a lonely moving dot and no curve. Decide on purpose whether the canvas keeps its history.

Exercises

  1. A living Lissajous. Animate the phase over time — phase = t * 0.3 — and clear each frame. The figure will breathe endlessly from line to ellipse to figure-eight and back. One number, infinite motion.
  2. Map a:b to the mouse. Set freq A from the mouse's x position and freq B from its y (round to integers). Sweeping the mouse becomes a tour through the entire family of closed Lissajous figures — a surprisingly addictive instrument.
  3. A palette gradient along t. Instead of one stroke color, draw the curve in short segments and color each by its t using the cosine palette, so the line shifts hue as it winds. Suddenly a single curve looks like ribbon.

What's next

Episode 06 — Fractals & Recursion: infinite detail from a few lines. We've been adding circles onto circles; next we'll have shapes that contain smaller copies of themselves, all the way down — trees, coastlines, snowflakes, and the Mandelbrot set — built from a function that calls itself. Same spirit (tiny rule, enormous output), brand-new kind of beauty.