Audio-Reactive From Zero · Episode 05
Waveform & Oscilloscope
Waveform & Oscilloscope is Episode 05 of Audio-Reactive From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.
Part of the MasterAllArts Creative 3D Roadmap .
The spectrum tells you what a sound is made of — how much bass, how much treble, where the energy lives. The waveform tells you what a sound looks like: the literal wiggle of the speaker cone, sample by sample, as it pushes air at you. It's the spectrum's quieter sibling — less colorful, harder to read at a glance — and yet it's the single most iconic image in all of audio. The green squiggle on an oscilloscope. The waveform strip in every editor. The thing that is the sound.
This episode lives entirely in the time domain. We'll take one
array — waveform, 256 bytes centered on 128 — and turn it into a real
oscilloscope with a grid and a midline, then a glowing phosphor ribbon, then a
persistence trail that smears like an old CRT scope, and finally a Lissajous
figure: plot one signal as X and another as Y and watch a hypnotic looping
curve draw itself. By the end you'll have the two most beautiful ways to see
sound that exist, both running on six lines of canvas 2D. Hit 🔊 enable
sound to feed it real audio — or just watch: it's alive right now.
What you're looking at
Every pixel on that canvas comes from one array of 256 numbers. There is no FFT here, no frequency math, no smoothing trickery — just the raw shape of the speaker's motion, redrawn sixty times a second. Three things are worth noticing before we build it up stage by stage:
- It's centered, not bottom-up. Unlike spectrum bars that grow from a floor, a waveform swings above and below a center line. Silence is a flat line through the middle, not an empty canvas.
- It scrolls. Watch the synthetic wave drift sideways. Each frame grabs a fresh window of samples that doesn't start at the same point in the wave's cycle, so the picture slides. Real scopes fix this with a trigger — we'll get there.
- Two signals make a shape. In the Lissajous stages, we stop plotting amplitude-over-time and instead plot one part of the wave against another. A line becomes a loop. That trick is the whole reason stereo "vectorscopes" look the way they do.
Step through the stage dropdown and the whole thing assembles in front
of you. Six states of one machine; six <h2>s below.
Stage 1 — Raw waveform line
The most literal possible drawing: walk across the canvas left to right, and for
each x read one byte of waveform and use it as y.
The only subtlety — and it's the pitfall that trips up everyone — is that the bytes are
centered on 128, not 0. A value of 128 means "speaker at rest." 255 is
full push, 0 is full pull. So before you can draw it you subtract 128 to get a signed
swing from −128 to +127, then scale that to pixels. Skip the subtraction and your wave
sits crammed against the bottom edge, because byte 128 maps to halfway down a canvas
whose origin is the top-left.
Stage 2 — Oscilloscope
Same line, but dressed as an instrument. We draw a faint grid and a
bright midline first, then the wave on top, anchored to the vertical
center and scaled by the gain slider. Now it reads like a tool: the
midline is "zero," divisions give you a sense of amplitude, and turning gain up
magnifies a quiet signal so you can actually see its shape. This is the layout every
hardware scope has used for seventy years, and it's maybe fifteen lines of canvas.
Stage 3 — Glowing ribbon
Two properties turn a thin technical line into something that looks like it's made
of light: a thicker lineWidth, and canvas's built-in
shadowBlur + shadowColor, which bleeds a colored halo around
everything you stroke. Add a vertical gradient stroke — cool at the
midline, hot at the peaks — and the same data now glows like a neon tube. It's a free,
one-property upgrade and it's the look that makes audio visualizers feel alive.
Stage 4 — Persistence
Here's the trick that makes it feel like a real scope. Instead of clearing
the canvas to black each frame, we paint a translucent black rectangle
over it. Old frames don't vanish — they fade. Each pixel the beam touched lingers for a
few frames and decays, exactly like the phosphor coating on a CRT tube. The
persistence slider controls how dark that overlay is: low values clear
almost completely (a crisp live wave); high values leave long ghostly trails that the
new wave carves through. Crank it up on a Lissajous and you get those gorgeous smoky
loops.
Stage 5 — Lissajous
Now the fun one. Stop thinking of the wave as height-over-time. Instead, for each
sample i, use waveform[i] as the X position
and waveform[i + shift] as the Y position — the same
signal, read at two slightly different points in time. Connect the dots and a flat line
becomes a curling, looping Lissajous figure. This is what a stereo
vectorscope shows when you feed it left-vs-right channels; here we fake the second
channel with a phase shift (and in the exercises, with bass-vs-treble). The shape
breathes with the music — circles when the two signals are a quarter-cycle apart, a
diagonal line when they're identical, chaos when they disagree.
Stage 6 — Polished combo
Everything at once. The oscilloscope ribbon rides the lower two-thirds of the
canvas; the Lissajous orbits in its own framed panel; persistence smears both; a shared
palette ties them together; and the wave's overall loudness drives the glow intensity.
This is the "screenshot you'd actually post" version — and it's still just the one
waveform array, drawn two different ways on top of a fading background.
How the code works
The whole episode reads from a single shared array. Whether it's filled by our
synthetic generator or by a live AnalyserNode, every stage draws against
waveform and nothing else — so the visuals are identical with or without
sound. First, getting a centered, scaled line onto the canvas:
// (a) waveform bytes are 0..255 CENTERED ON 128. Subtract it.
function drawWave(ctx, wave, w, h, gain) {
ctx.beginPath();
const mid = h / 2;
for (let i = 0; i < wave.length; i++) {
const x = (i / (wave.length - 1)) * w;
const v = (wave[i] - 128) / 128; // → −1 .. +1, signed
const y = mid - v * mid * gain; // center, then scale by gain
i === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
}
ctx.stroke();
}
That's stages 1 and 2 (the grid and midline are just a few extra
moveTo/lineTo calls before this). To make it glow, we lean on
two canvas properties and a gradient — no shaders, no libraries:
// (b) the glow: shadowBlur + shadowColor, plus a vertical gradient stroke
const grad = ctx.createLinearGradient(0, 0, 0, h);
grad.addColorStop(0, '#f472b6'); // hot pink at the top peaks
grad.addColorStop(0.5, '#38bdf8'); // cool cyan through the midline
grad.addColorStop(1, '#f472b6');
ctx.strokeStyle = grad;
ctx.lineWidth = 2.5 * dpr;
ctx.lineJoin = 'round';
if (glowOn) {
ctx.shadowBlur = 16 * dpr; // the halo radius
ctx.shadowColor = '#38bdf8'; // the halo color (cyan)
}
drawWave(ctx, waveform, w, h, gain);
ctx.shadowBlur = 0; // reset, or EVERYTHING glows
Persistence is the smallest, most magical change. Don't clear the canvas — fade it. Painting a low-alpha black rectangle each frame leaves a decaying trail of every past frame: instant phosphor:
// (c) persistence: a translucent fillRect INSTEAD of a hard clear
function fade(ctx, w, h, persist) {
// persist=0 → almost-opaque wipe (crisp); persist→1 → long ghost trails
ctx.fillStyle = `rgba(10,10,12,${1 - persist})`;
ctx.fillRect(0, 0, w, h);
}
// (vs. the non-persistent path: ctx.clearRect(0,0,w,h) — wipes every frame)
And the Lissajous: plot the wave against a time-shifted copy of itself. One signal,
read twice, becomes a 2D curve. Map both bytes from 0..255 into the canvas
box, connect the points, done:
// (d) Lissajous: x from wave[i], y from wave[(i+shift)%N]
function drawLissajous(ctx, wave, cx, cy, radius, gain, shift) {
const N = wave.length;
ctx.beginPath();
for (let i = 0; i < N; i++) {
const vx = (wave[i] - 128) / 128; // signal A → X
const vy = (wave[(i + shift) % N] - 128) / 128; // signal B (phase-shifted) → Y
const x = cx + vx * radius * gain;
const y = cy + vy * radius * gain;
i === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
}
ctx.stroke();
}
The synthetic generator that keeps this alive with no AudioContext fills
both spectrum and waveform from a fake ~128 BPM track. We
only read waveform this episode, but we fill both so the
spectrum episode's helpers stay drop-in compatible —
one data model, every episode. When you press enable sound, the only
thing that changes is who fills the array: a real analyser's
getByteTimeDomainData takes over, and every draw function above keeps
working untouched.
Common pitfalls
- Forgetting to subtract 128. This is the waveform bug.
The bytes are centered on 128, so a plain
y = wave[i]pins a resting signal halfway down the canvas and clips the bottom half off-screen. Always(wave[i] - 128) / 128to get a signed −1..+1 swing first, then scale. - Gain that clips or vanishes. A quiet signal scaled by gain 1 is a
nearly flat line; a loud one at gain 3 slams into the top and bottom edges and looks
like a square wave. Expose gain as a slider (we do) and consider clamping
yto the canvas so peaks fold instead of disappearing. - The wave scrolls / jitters horizontally. Each frame's window of samples starts at an arbitrary phase, so the picture drifts sideways frame to frame. That's not a bug — it's the absence of a trigger. Real scopes wait for the signal to cross zero going upward before they start drawing, which locks the wave in place. It's an optional stabilizer (see the first exercise), not a correctness fix.
- A boring Lissajous. If you plot the wave against an identical copy (shift = 0), X always equals Y and you get a straight diagonal line — never a loop. A Lissajous needs two genuinely different signals: a phase shift (what we do), the left vs. right stereo channels, or bass vs. treble bands. No difference, no figure.
- The whole canvas glows.
shadowBluris sticky — it applies to every draw call until you reset it. Setctx.shadowBlur = 0after the glowing stroke or your grid, text, and even the fade rectangle pick up an expensive halo and the frame rate tanks. - Persistence looks like a smear, not a trail. If the fade alpha is too low the canvas never fully clears and old frames pile into mud. Keep the wipe alpha at least ~0.05 (i.e. persistence ≤ 0.95) so the oldest frames actually die.
Exercises
- Add a zero-crossing trigger. Before drawing, scan
waveformfor the first index where it rises through 128 (wave[i] < 128 && wave[i+1] >= 128) and start yourxloop from there instead of 0. The wave will snap rock-steady, exactly like a hardware scope's "trigger" knob. Compare it side by side with the free-running version — the difference is dramatic. - Color by amplitude. Instead of a fixed gradient, choose the
stroke color per frame from the wave's peak-to-peak swing: quiet = deep blue, loud =
hot magenta. Compute
max(wave) - min(wave)once andlerptwo colors with it (or build anhsl()string). Now the scope literally changes color with the dynamics of the track. - Make the Lissajous react to bass. Read the low end of the
spectrum array (it's already being filled) and use that energy to drive the
Lissajous
radius— so the figure pulses bigger on every kick drum. This quietly reunites the two domains: the spectrum sizes a shape the waveform draws.
What's next
Episode 06 — Audio-Reactive Particles. We stop drawing lines and start spawning thousands of points, then feed the spectrum into a particle storm: bass kicks burst new particles into existence, treble shakes them, the overall swell drags them through a flow field. Everything you've learned about reading these two arrays becomes the force that moves a living cloud. It's the most viral payoff in the series.