// Small canvas plotting helpers: line plots (linear or log x), spectrogram images, bars. export interface Series { x: ArrayLike; y: ArrayLike; color: string; label?: string; width?: number; dash?: number[]; points?: boolean; } export interface Axes { xlog?: boolean; xmin?: number; xmax?: number; ymin?: number; ymax?: number; xlabel?: string; ylabel?: string; marks?: { x: number; label?: string }[]; } const css = (name: string) => getComputedStyle(document.documentElement).getPropertyValue(name).trim() || "#888"; export function setupCanvas(c: HTMLCanvasElement): { ctx: CanvasRenderingContext2D; w: number; h: number } { const dpr = window.devicePixelRatio || 1; const w = c.clientWidth, h = c.clientHeight; if (c.width !== Math.round(w * dpr) || c.height !== Math.round(h * dpr)) { c.width = Math.round(w * dpr); c.height = Math.round(h * dpr); } const ctx = c.getContext("2d")!; ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, w, h); return { ctx, w, h }; } function niceTicks(lo: number, hi: number, n = 5): number[] { const span = hi - lo; if (!(span > 0)) return [lo]; const step0 = span / n, mag = Math.pow(10, Math.floor(Math.log10(step0))); const step = [1, 2, 5, 10].map((m) => m * mag).find((s) => s >= step0) ?? mag * 10; const out: number[] = []; for (let v = Math.ceil(lo / step) * step; v <= hi + 1e-9 * step; v += step) out.push(+v.toPrecision(12)); return out; } function logTicks(lo: number, hi: number): number[] { const out: number[] = []; for (let e = Math.floor(Math.log10(lo)); e <= Math.ceil(Math.log10(hi)); e++) for (const m of [1, 2, 5]) { const v = m * Math.pow(10, e); if (v >= lo && v <= hi) out.push(v); } return out; } const fmt = (v: number) => (Math.abs(v) >= 1000 ? `${+(v / 1000).toPrecision(3)}k` : `${+v.toPrecision(3)}`); export function linePlot(c: HTMLCanvasElement, series: Series[], ax: Axes = {}): void { const { ctx, w, h } = setupCanvas(c); const padL = 44, padR = 10, padT = 10, padB = 26; let xmin = ax.xmin ?? Infinity, xmax = ax.xmax ?? -Infinity, ymin = ax.ymin ?? Infinity, ymax = ax.ymax ?? -Infinity; for (const s of series) for (let i = 0; i < s.x.length; i++) { const x = s.x[i], y = s.y[i]; if (!isFinite(x) || !isFinite(y) || (ax.xlog && x <= 0)) continue; if (ax.xmin === undefined) xmin = Math.min(xmin, x); if (ax.xmax === undefined) xmax = Math.max(xmax, x); if (ax.ymin === undefined) ymin = Math.min(ymin, y); if (ax.ymax === undefined) ymax = Math.max(ymax, y); } if (!isFinite(xmin) || !isFinite(xmax)) { xmin = 0; xmax = 1; } if (!isFinite(ymin) || !isFinite(ymax)) { ymin = 0; ymax = 1; } if (ymax === ymin) { ymax += 1; ymin -= 1; } const X = (x: number) => padL + (w - padL - padR) * (ax.xlog ? Math.log(x / xmin) / Math.log(xmax / xmin) : (x - xmin) / (xmax - xmin)); const Y = (y: number) => padT + (h - padT - padB) * (1 - (y - ymin) / (ymax - ymin)); ctx.font = "11px system-ui, sans-serif"; ctx.strokeStyle = css("--grid"); ctx.fillStyle = css("--muted"); ctx.lineWidth = 1; for (const t of ax.xlog ? logTicks(xmin, xmax) : niceTicks(xmin, xmax, 6)) { const x = X(t); ctx.beginPath(); ctx.moveTo(x, padT); ctx.lineTo(x, h - padB); ctx.stroke(); ctx.textAlign = "center"; ctx.fillText(fmt(t), x, h - padB + 13); } for (const t of niceTicks(ymin, ymax, 4)) { const y = Y(t); ctx.beginPath(); ctx.moveTo(padL, y); ctx.lineTo(w - padR, y); ctx.stroke(); ctx.textAlign = "right"; ctx.fillText(fmt(t), padL - 4, y + 4); } if (ax.xlabel) { ctx.textAlign = "right"; ctx.fillText(ax.xlabel, w - padR, h - 2); } if (ax.ylabel) { ctx.save(); ctx.translate(10, padT + 2); ctx.rotate(-Math.PI / 2); ctx.textAlign = "right"; ctx.fillText(ax.ylabel, 0, 0); ctx.restore(); } ctx.save(); ctx.beginPath(); ctx.rect(padL, padT, w - padL - padR, h - padT - padB); ctx.clip(); for (const mk of ax.marks ?? []) { if (mk.x < xmin || mk.x > xmax) continue; const x = X(mk.x); ctx.strokeStyle = css("--mark"); ctx.setLineDash([2, 3]); ctx.beginPath(); ctx.moveTo(x, padT); ctx.lineTo(x, h - padB); ctx.stroke(); ctx.setLineDash([]); if (mk.label) { ctx.fillStyle = css("--muted"); ctx.textAlign = "left"; ctx.fillText(mk.label, x + 2, padT + 10); } } for (const s of series) { ctx.strokeStyle = s.color; ctx.fillStyle = s.color; ctx.lineWidth = s.width ?? 1.5; ctx.setLineDash(s.dash ?? []); if (s.points) { for (let i = 0; i < s.x.length; i++) { const x = s.x[i], y = s.y[i]; if (!isFinite(y) || !isFinite(x)) continue; ctx.beginPath(); ctx.arc(X(x), Y(y), 2.5, 0, 2 * Math.PI); ctx.fill(); } continue; } ctx.beginPath(); let pen = false; for (let i = 0; i < s.x.length; i++) { const x = s.x[i], y = s.y[i]; if (!isFinite(y) || !isFinite(x) || (ax.xlog && x <= 0)) { pen = false; continue; } const px = X(x), py = Y(Math.max(ymin - 1e3, Math.min(ymax + 1e3, y))); if (pen) ctx.lineTo(px, py); else { ctx.moveTo(px, py); pen = true; } } ctx.stroke(); } ctx.setLineDash([]); ctx.restore(); // legend let lx = padL + 6; for (const s of series) { if (!s.label) continue; ctx.fillStyle = s.color; ctx.fillRect(lx, padT + 4, 10, 3); ctx.fillStyle = css("--fg"); ctx.textAlign = "left"; ctx.fillText(s.label, lx + 13, padT + 9); lx += 20 + ctx.measureText(s.label).width; } } /** Spectrogram image: frames (dB) on a log-frequency axis from fmin to fmax, dynamic range rangeDb. */ export function spectrogramPlot(c: HTMLCanvasElement, frames: Float64Array[], fs: number, n: number, hop: number, opts: { fmin?: number; fmax?: number; rangeDb?: number; title?: string } = {}): void { const { ctx, w, h } = setupCanvas(c); const padL = 44, padB = 18, padT = 4; const fmin = opts.fmin ?? 30, fmax = opts.fmax ?? 6000, range = opts.rangeDb ?? 80; if (!frames.length) return; let mx = -Infinity; for (const f of frames) for (let i = 0; i < f.length; i++) mx = Math.max(mx, f[i]); const iw = Math.max(1, Math.floor(w - padL)), ih = Math.max(1, Math.floor(h - padB - padT)); const img = ctx.createImageData(iw, ih); const df = fs / n; for (let px = 0; px < iw; px++) { const fr = frames[Math.min(frames.length - 1, Math.floor((px / iw) * frames.length))]; for (let py = 0; py < ih; py++) { const f = fmin * Math.pow(fmax / fmin, 1 - py / ih); const b = f / df, b0 = Math.floor(b), t = b - b0; const v = (fr[b0] ?? -300) * (1 - t) + (fr[b0 + 1] ?? -300) * t; const z = Math.max(0, Math.min(1, (v - mx + range) / range)); const o = 4 * (py * iw + px); // perceptual-ish ramp: dark blue -> teal -> yellow img.data[o] = Math.round(255 * Math.min(1, Math.max(0, 1.8 * z - 0.6))); img.data[o + 1] = Math.round(255 * Math.pow(z, 0.9)); img.data[o + 2] = Math.round(255 * Math.max(0, 0.55 - 0.5 * z + 0.3 * Math.sin(Math.PI * z))); img.data[o + 3] = 255; } } // putImageData ignores the transform, so go through a canvas and drawImage const tmp = document.createElement("canvas"); tmp.width = iw; tmp.height = ih; tmp.getContext("2d")!.putImageData(img, 0, 0); ctx.imageSmoothingEnabled = false; ctx.drawImage(tmp, padL, padT, iw, ih); ctx.font = "11px system-ui, sans-serif"; ctx.fillStyle = css("--muted"); for (const f of logTicks(fmin, fmax)) { const y = padT + ih * (1 - Math.log(f / fmin) / Math.log(fmax / fmin)); ctx.textAlign = "right"; ctx.fillText(fmt(f), padL - 4, y + 4); } const dur = (frames.length * hop) / fs; for (const t of niceTicks(0, dur, 6)) { ctx.textAlign = "center"; ctx.fillText(`${t}s`, padL + (iw * t) / dur, h - 4); } if (opts.title) { ctx.fillStyle = "#fff"; ctx.textAlign = "left"; ctx.fillText(opts.title, padL + 6, padT + 13); } }