Audio-Reactive From Zero · Episode 07

Spectrogram & Radial

Spectrogram & Radial is Episode 07 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 .

Episode 07 · Audio-Reactive From Zero

There are two pictures that instantly say "this is audio." The first is the spectrogram: a scrolling waterfall where time runs sideways, frequency runs up, and brightness is loudness — the exact view you see in Audacity, Ableton, or a voice-memo app while it listens. The second is the radial visualizer: the spectrum wrapped into a glowing ring, bars blooming outward like a tiny sun, the look on a thousand music-video loops and lock screens. Both are iconic. Both look hard. Both are built from the same 256-number array we've been carrying since Episode 01.

This episode builds them side by side, in six felt stages, with raw canvas 2D and zero dependencies. You'll learn the one performance trick that makes a real-time spectrogram possible — scroll the canvas by a single pixel and paint only the new column, never re-reading the whole image — and a magnitude-to-color colormap that turns a grey histogram into something that glows. By the last stage we drop the radial sun on top of the spectrogram and they share a palette. It's alive the moment the page loads, on a synthetic beat; press 🔊 enable sound and it switches to a real Web Audio graph, mic, or a file.

0 fps
spectrogram scrolling · synthetic beat
Web Audio · synthetic (no gesture yet)
Web Audio · synthetic
One spectrum frame drawn as a vertical strip of colored cells — magnitude becomes color.

What you're looking at

Every frame, two Uint8Arrays get filled — spectrum (256 frequency magnitudes, 0..255, bass at index 0) and waveform (256 time-domain samples around 128). That's the entire data model from Episode 01, unchanged. The spectrogram and the radial sun are just two different ways of arranging the same numbers in space: the spectrogram lays frequency along a vertical line and lets time scroll; the radial lays frequency along a circle and lets magnitude push outward. Switch stages with the stage dropdown and watch one array become two completely different instruments.

The scroll speed slider controls how many pixels the waterfall shifts per frame (faster = more time on screen, coarser detail). palette swaps the magnitude→color ramp shared by both halves. radial radius sets the inner radius of the ring. And 🔊 enable sound upgrades the synthetic feed to a live analyser — synth, mic, or a file you pick — falling back silently to synthetic if the browser says no.

Stage 1 — One spectrum column

Before anything scrolls, draw a single frame as a vertical strip. Walk the 256 bins from bottom (bass) to top (treble), and for each bin fill a small rectangle whose color comes from its magnitude. This is one column of a spectrogram — a frozen slice of "now." It already pulses with the beat: the bass cells at the bottom flash on every kick. Nothing here knows about time yet; we're just proving that magnitude → color → a stack of cells reads as a frequency profile.

Stage 2 — Spectrogram waterfall

Now add time. The trick that makes this real-time: each frame, shift the entire canvas left by a few pixels with one drawImage(canvas, -dx, 0) call, then paint the fresh column into the gap on the right. The GPU does the scroll for free. History slides off the left edge; the newest moment is always at the right. Suddenly you can see the melody move — bass thumps stack into a steady band at the bottom, treble sparkle flickers along the top. This is the canonical audio-software view.

Stage 3 — Color-mapped

Stage 2 used a quick grey-ish ramp, and quiet passages vanish into the black background — bad. A real spectrogram uses a perceptual colormap: a curve through color space (inferno, viridis…) where even low magnitudes get a dark-but-visible color and peaks blow out to white-hot. Now the faint harmonics between the loud bands appear, the texture of the sound shows up, and the whole thing looks like an instrument instead of a security camera. Try the palette dropdown — same data, four different moods.

Stage 4 — Radial bars

Same array, new geometry. Instead of stacking bins vertically, lay them around a circle. Bin i sits at angle i / N · 2π; its magnitude becomes the length of a bar pointing outward from a center ring. Bass occupies one arc, treble the rest, and the whole thing breathes with the music. This is the polar EQ — the bones of every "audio ring" you've seen. The radial radius slider moves the inner circle the bars grow from.

Stage 5 — Radial sun

Three touches turn a bare ring into the audio sun. First, mirror the spectrum across the vertical axis so the ring is symmetric (left half = right half) — symmetry reads as "designed." Second, add glow: a soft additive bloom (shadowBlur plus a translucent over-draw) so loud bars halo. Third, thread the waveform as a thin wobbling ring just inside the bars, so the quiet center is alive too. The result blooms and pulses like a little star reacting to the track.

Stage 6 — Combined

The payoff: run the spectrogram as a full-canvas backdrop and float the radial sun on top, both pulling from the same colormap so they look like one design instead of two stickers. The waterfall gives a sense of history and motion behind the sun's instantaneous bloom. This is a complete, shippable visualizer scene — and a direct preview of next episode's full music visualizer, which composites several of these layers at once.

How the code works

Everything below reads from the shared spectrum/waveform arrays. Whether they're filled by the synthetic generator or a live AnalyserNode is the only thing that changes — the drawing code never knows the difference.

(a) The efficient scroll — shift the canvas, draw one column

The naïve spectrogram reads the whole canvas with getImageData, copies every pixel one row over, and writes it back with putImageData every frame. That's millions of pixels through JavaScript sixty times a second — instant jank. The fix is to let the canvas scroll itself: drawImage the canvas onto itself, offset by the scroll amount. Then you only ever author the single new column. Note the shift is in device pixels (dx · dpr) so it scrolls the same visual speed on retina and non-retina screens.

// Per frame: scroll the whole canvas left by dx device-px, then draw ONE new column.
// drawImage(canvas, ...) onto itself is GPU-cheap. NEVER getImageData/putImageData here.
function scrollAndDrawColumn(ctx, spectrum, dxCss) {
  const dpr = ctx._dpr;
  const W = ctx.canvas.width, H = ctx.canvas.height;   // device px
  const dx = Math.max(1, Math.round(dxCss * dpr));      // shift ≥ 1 real px

  // 1) slide existing pixels left by dx (the canvas scrolls itself)
  ctx.drawImage(ctx.canvas, -dx, 0);

  // 2) paint only the freshly-exposed strip on the right edge
  const x = W - dx;
  const N = spectrum.length, cellH = H / N;
  for (let i = 0; i < N; i++) {
    const mag = spectrum[i] / 255;                     // 0..1
    ctx.fillStyle = colormap(mag);                  // (b) below
    // bass (i=0) at the BOTTOM, treble at the top → flip y
    const y = H - (i + 1) * cellH;
    ctx.fillRect(x, y, dx, cellH + 1);             // +1 avoids hairline gaps
  }
}

(b) Magnitude → color: a perceptual-ish colormap

A colormap is just a function from one number (0..1) to an RGB color. The cheapest good-looking one is a handful of anchor colors you linearly interpolate between — a stripped-down inferno/viridis. The key rule: the bottom of the ramp is a dark color, not pure black, so quiet detail stays visible against the black canvas. We precompute a 256-entry lookup table once so the per-pixel cost is a single array read, not a lerp.

// Anchor stops per palette (t, [r,g,b]). Low end is dark-but-not-black on purpose.
const PALETTES = {
  inferno: [[0,[4,2,18]],[.25,[86,15,80]],[.5,[186,54,59]],
            [.75,[246,148,29]],[1,[252,255,164]]],
  viridis: [[0,[8,12,40]],[.25,[59,82,139]],[.5,[33,145,140]],
            [.75,[94,201,98]],[1,[253,231,37]]],
  /* ...ice, mono... */
};

// Build a 256-entry LUT of "r,g,b" strings once, on palette change.
function buildLUT(stops) {
  const lut = new Array(256);
  for (let j = 0; j < 256; j++) {
    const t = j / 255;
    let a = stops[0], b = stops[stops.length - 1];
    for (let k = 0; k < stops.length - 1; k++)
      if (t >= stops[k][0] && t <= stops[k+1][0]) { a = stops[k]; b = stops[k+1]; break; }
    const f = (t - a[0]) / (b[0] - a[0] || 1);
    const r = a[1][0] + (b[1][0] - a[1][0]) * f;
    const g = a[1][1] + (b[1][1] - a[1][1]) * f;
    const bl = a[1][2] + (b[1][2] - a[1][2]) * f;
    lut[j] = `rgb(${r|0},${g|0},${bl|0})`;
  }
  return lut;
}
const colormap = (m) => lut[(m * 255) | 0];   // m in 0..1 → cached color string

(c) The polar / radial bar layout

To wrap the spectrum around a circle, convert each bin's index into an angle and its magnitude into a radius, then draw a line (or wedge) from the inner ring outward. Music is logarithmic, so reading bins linearly crams all the interesting bass into a sliver — we sample the array on a mild log curve so bass gets more of the circle. We rotate so angle 0 starts at the top, which just looks better.

// Lay N bars around a circle of inner radius r0, growing outward by magnitude.
function drawRadialBars(ctx, spectrum, cx, cy, r0, maxLen) {
  const N = spectrum.length, bars = 96;            // fewer, fatter bars read better
  ctx.lineWidth = (Math.PI * 2 * r0) / bars * 0.7;
  ctx.lineCap = 'round';
  for (let b = 0; b < bars; b++) {
    // LOG-frequency sampling: bass (low i) gets more bars than treble
    const frac = b / bars;
    const idx = Math.min(N - 1, Math.floor((Math.pow(10, frac) - 1) / 9 * N));
    const mag = spectrum[idx] / 255;
    const ang = frac * Math.PI * 2 - Math.PI / 2;   // start at top
    const len = r0 + mag * maxLen;
    ctx.strokeStyle = colormap(mag);
    ctx.beginPath();
    ctx.moveTo(cx + Math.cos(ang) * r0,  cy + Math.sin(ang) * r0);
    ctx.lineTo(cx + Math.cos(ang) * len, cy + Math.sin(ang) * len);
    ctx.stroke();
  }
}

(d) The mirrored, glowing radial sun

The sun is the radial bars made symmetric and luminous. We draw the bars over a half circle and mirror them to the other half so the figure is bilaterally symmetric, switch the context into additive blend ('lighter'), and fake the glow with a wide faint halo stroke under a thin bright core — a translucent over-draw that blooms beautifully and costs almost nothing. (A per-stroke shadowBlur gives the same look but re-blurs every bar 60×/second — it tanked this demo to 31fps until we switched to the over-draw.) Then trace the waveform as a thin closed ring inside. The bloom is what sells it — without it, it's just a wheel of sticks.

// Mirror across the vertical axis + additive glow + an inner waveform ring.
function drawSun(ctx, spectrum, waveform, cx, cy, r0, maxLen) {
  ctx.save();
  ctx.globalCompositeOperation = 'lighter';       // additive bloom (no shadowBlur — too slow per-stroke)

  const N = spectrum.length, half = 64;
  for (let b = 0; b < half; b++) {
    const frac = b / half;
    const idx = Math.min(N - 1, Math.floor((Math.pow(10, frac) - 1) / 9 * N));
    const mag = spectrum[idx] / 255;
    const col = colormap(mag);
    const a0 = frac * Math.PI - Math.PI / 2;            // right half, top→bottom
    const len = r0 + mag * maxLen;
    ctx.strokeStyle = col;
    for (const s of [1, -1]) {                       // s=1 right, s=-1 mirror left
      const ang = Math.PI / 2 + s * (a0 + Math.PI / 2) * -1;
      const x0 = cx + Math.cos(ang)*r0, y0 = cy + Math.sin(ang)*r0;
      const x1 = cx + Math.cos(ang)*len, y1 = cy + Math.sin(ang)*len;
      ctx.globalAlpha = 0.16; ctx.lineWidth = wide;  // faint halo
      ctx.beginPath(); ctx.moveTo(x0,y0); ctx.lineTo(x1,y1); ctx.stroke();
      ctx.globalAlpha = 1; ctx.lineWidth = core;     // bright core
      ctx.beginPath(); ctx.moveTo(x0,y0); ctx.lineTo(x1,y1); ctx.stroke();
    }
  }

  // inner waveform ring — the quiet center stays alive
  ctx.beginPath();
  for (let i = 0; i <= waveform.length; i++) {
    const w = (waveform[i % waveform.length] - 128) / 128;
    const rr = r0 * (0.78 + w * 0.12);
    const a = (i / waveform.length) * Math.PI * 2;
    const fn = i === 0 ? 'moveTo' : 'lineTo';
    ctx[fn](cx + Math.cos(a) * rr, cy + Math.sin(a) * rr);
  }
  ctx.closePath(); ctx.strokeStyle = 'rgba(255,255,255,0.55)'; ctx.stroke();
  ctx.restore();
}

Common pitfalls

  • Re-reading the whole canvas every frame. The number-one spectrogram mistake is getImageData → shift rows in JS → putImageData. That's a full-frame CPU copy 60×/sec and it will drop frames. Always scroll with a single drawImage(canvas, -dx, 0) (or an offscreen ring-buffer canvas) and author only the one new column.
  • Black-on-black colormap. If your ramp starts at pure black, every quiet bin disappears into the background and the spectrogram looks empty between kicks. Start the ramp at a dark-but-visible color and let it climb to white-hot. A perceptual ramp (inferno/viridis) does this for free.
  • Linear frequency on the radial. Bass lives in the first few percent of the bins, so a linear wrap-around buries the whole melody in one sliver and leaves a huge empty treble arc. Sample the array on a log curve (as in (c)) so bass gets a fair share of the circle.
  • Forgetting DPR in the 1px shift. The scroll amount is in device pixels. On a 2× display, shifting by 1 instead of 1·dpr scrolls at half speed and slowly blurs the image as fractional offsets accumulate. Shift by Math.round(dx · dpr) and you're safe.
  • Glow with the wrong blend or no reset. The sun's bloom needs globalCompositeOperation = 'lighter' (additive) and a shadowBlur — but wrap it in save()/restore() or the additive mode bleeds into the next thing you draw and the whole canvas washes out.
  • AudioContext starts suspended. It needs a user gesture to resume(). That's exactly why the demo runs on the synthetic feed first and only swaps to the live analyser inside the enable-sound click — and falls back to synthetic in a catch if anything goes wrong.

Exercises

  1. Log-frequency spectrogram rows. The waterfall in this episode uses linear bin rows (bass crammed at the bottom). Map row i through the same pow(10, ...) curve used on the radial so each octave gets equal vertical space — now bass detail spreads out and the spectrogram matches what music software actually shows.
  2. Freeze / scrub the waterfall. Keep the last N columns in an offscreen canvas (a ring buffer) instead of letting them scroll off-screen forever. Add a freeze checkbox that stops advancing and a slider that scrubs a viewport window across the stored history — you've built a mini time-machine.
  3. Bass-pulsing sun radius. Average the lowest ~12% of spectrum into a bass value, smooth it with a lerp, and add it to the sun's inner radius r0 each frame. The whole sun should now breathe on the kick — the single most satisfying tweak in the episode.

What's next

Episode 08 — The Music Visualizer (Season Finale). We take every layer the series built — bars, waveform, particles, beat flashes, the spectrogram and the radial sun from today — and composite them into one full-screen, beat-aware music visualizer you'd actually be proud to loop behind a track. The combined stage you just saw is the seed; the finale grows it into the whole thing.