1// Small canvas plotting helpers: line plots (linear or log x), spectrogram images, bars.
3export interface Series {
4 x: ArrayLike<number>;
5 y: ArrayLike<number>;
6 color: string;
7 label?: string;
8 width?: number;
9 dash?: number[];
10 points?: boolean;
11}
13export interface Axes {
14 xlog?: boolean;
15 xmin?: number;
16 xmax?: number;
17 ymin?: number;
18 ymax?: number;
19 xlabel?: string;
20 ylabel?: string;
21 marks?: { x: number; label?: string }[];
22}
24const css = (name: string) => getComputedStyle(document.documentElement).getPropertyValue(name).trim() || "#888";
26export function setupCanvas(c: HTMLCanvasElement): { ctx: CanvasRenderingContext2D; w: number; h: number } {
27 const dpr = window.devicePixelRatio || 1;
28 const w = c.clientWidth, h = c.clientHeight;
29 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); }
30 const ctx = c.getContext("2d")!;
31 ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
32 ctx.clearRect(0, 0, w, h);
33 return { ctx, w, h };
34}
36function niceTicks(lo: number, hi: number, n = 5): number[] {
37 const span = hi - lo;
38 if (!(span > 0)) return [lo];
39 const step0 = span / n, mag = Math.pow(10, Math.floor(Math.log10(step0)));
40 const step = [1, 2, 5, 10].map((m) => m * mag).find((s) => s >= step0) ?? mag * 10;
41 const out: number[] = [];
42 for (let v = Math.ceil(lo / step) * step; v <= hi + 1e-9 * step; v += step) out.push(+v.toPrecision(12));
43 return out;
44}
46function logTicks(lo: number, hi: number): number[] {
47 const out: number[] = [];
48 for (let e = Math.floor(Math.log10(lo)); e <= Math.ceil(Math.log10(hi)); e++)
49 for (const m of [1, 2, 5]) { const v = m * Math.pow(10, e); if (v >= lo && v <= hi) out.push(v); }
50 return out;
51}
53const fmt = (v: number) => (Math.abs(v) >= 1000 ? `${+(v / 1000).toPrecision(3)}k` : `${+v.toPrecision(3)}`);
55export function linePlot(c: HTMLCanvasElement, series: Series[], ax: Axes = {}): void {
56 const { ctx, w, h } = setupCanvas(c);
57 const padL = 44, padR = 10, padT = 10, padB = 26;
58 let xmin = ax.xmin ?? Infinity, xmax = ax.xmax ?? -Infinity, ymin = ax.ymin ?? Infinity, ymax = ax.ymax ?? -Infinity;
59 for (const s of series) for (let i = 0; i < s.x.length; i++) {
60 const x = s.x[i], y = s.y[i];
61 if (!isFinite(x) || !isFinite(y) || (ax.xlog && x <= 0)) continue;
62 if (ax.xmin === undefined) xmin = Math.min(xmin, x);
63 if (ax.xmax === undefined) xmax = Math.max(xmax, x);
64 if (ax.ymin === undefined) ymin = Math.min(ymin, y);
65 if (ax.ymax === undefined) ymax = Math.max(ymax, y);
66 }
67 if (!isFinite(xmin) || !isFinite(xmax)) { xmin = 0; xmax = 1; }
68 if (!isFinite(ymin) || !isFinite(ymax)) { ymin = 0; ymax = 1; }
69 if (ymax === ymin) { ymax += 1; ymin -= 1; }
70 const X = (x: number) => padL + (w - padL - padR) * (ax.xlog ? Math.log(x / xmin) / Math.log(xmax / xmin) : (x - xmin) / (xmax - xmin));
71 const Y = (y: number) => padT + (h - padT - padB) * (1 - (y - ymin) / (ymax - ymin));
72 ctx.font = "11px system-ui, sans-serif";
73 ctx.strokeStyle = css("--grid"); ctx.fillStyle = css("--muted"); ctx.lineWidth = 1;
74 for (const t of ax.xlog ? logTicks(xmin, xmax) : niceTicks(xmin, xmax, 6)) {
75 const x = X(t);
76 ctx.beginPath(); ctx.moveTo(x, padT); ctx.lineTo(x, h - padB); ctx.stroke();
77 ctx.textAlign = "center"; ctx.fillText(fmt(t), x, h - padB + 13);
78 }
79 for (const t of niceTicks(ymin, ymax, 4)) {
80 const y = Y(t);
81 ctx.beginPath(); ctx.moveTo(padL, y); ctx.lineTo(w - padR, y); ctx.stroke();
82 ctx.textAlign = "right"; ctx.fillText(fmt(t), padL - 4, y + 4);
83 }
84 if (ax.xlabel) { ctx.textAlign = "right"; ctx.fillText(ax.xlabel, w - padR, h - 2); }
85 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(); }
86 ctx.save();
87 ctx.beginPath(); ctx.rect(padL, padT, w - padL - padR, h - padT - padB); ctx.clip();
88 for (const mk of ax.marks ?? []) {
89 if (mk.x < xmin || mk.x > xmax) continue;
90 const x = X(mk.x);
91 ctx.strokeStyle = css("--mark"); ctx.setLineDash([2, 3]);
92 ctx.beginPath(); ctx.moveTo(x, padT); ctx.lineTo(x, h - padB); ctx.stroke();
93 ctx.setLineDash([]);
94 if (mk.label) { ctx.fillStyle = css("--muted"); ctx.textAlign = "left"; ctx.fillText(mk.label, x + 2, padT + 10); }
95 }
96 for (const s of series) {
97 ctx.strokeStyle = s.color; ctx.fillStyle = s.color; ctx.lineWidth = s.width ?? 1.5;
98 ctx.setLineDash(s.dash ?? []);
99 if (s.points) {
100 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(); }
101 continue;
102 }
103 ctx.beginPath();
104 let pen = false;
105 for (let i = 0; i < s.x.length; i++) {
106 const x = s.x[i], y = s.y[i];
107 if (!isFinite(y) || !isFinite(x) || (ax.xlog && x <= 0)) { pen = false; continue; }
108 const px = X(x), py = Y(Math.max(ymin - 1e3, Math.min(ymax + 1e3, y)));
109 if (pen) ctx.lineTo(px, py); else { ctx.moveTo(px, py); pen = true; }
110 }
111 ctx.stroke();
112 }
113 ctx.setLineDash([]);
114 ctx.restore();
115 // legend
116 let lx = padL + 6;
117 for (const s of series) {
118 if (!s.label) continue;
119 ctx.fillStyle = s.color; ctx.fillRect(lx, padT + 4, 10, 3);
120 ctx.fillStyle = css("--fg"); ctx.textAlign = "left"; ctx.fillText(s.label, lx + 13, padT + 9);
121 lx += 20 + ctx.measureText(s.label).width;
122 }
123}
125/** Spectrogram image: frames (dB) on a log-frequency axis from fmin to fmax, dynamic range rangeDb. */
126export function spectrogramPlot(c: HTMLCanvasElement, frames: Float64Array[], fs: number, n: number, hop: number, opts: { fmin?: number; fmax?: number; rangeDb?: number; title?: string } = {}): void {
127 const { ctx, w, h } = setupCanvas(c);
128 const padL = 44, padB = 18, padT = 4;
129 const fmin = opts.fmin ?? 30, fmax = opts.fmax ?? 6000, range = opts.rangeDb ?? 80;
130 if (!frames.length) return;
131 let mx = -Infinity;
132 for (const f of frames) for (let i = 0; i < f.length; i++) mx = Math.max(mx, f[i]);
133 const iw = Math.max(1, Math.floor(w - padL)), ih = Math.max(1, Math.floor(h - padB - padT));
134 const img = ctx.createImageData(iw, ih);
135 const df = fs / n;
136 for (let px = 0; px < iw; px++) {
137 const fr = frames[Math.min(frames.length - 1, Math.floor((px / iw) * frames.length))];
138 for (let py = 0; py < ih; py++) {
139 const f = fmin * Math.pow(fmax / fmin, 1 - py / ih);
140 const b = f / df, b0 = Math.floor(b), t = b - b0;
141 const v = (fr[b0] ?? -300) * (1 - t) + (fr[b0 + 1] ?? -300) * t;
142 const z = Math.max(0, Math.min(1, (v - mx + range) / range));
143 const o = 4 * (py * iw + px);
144 // perceptual-ish ramp: dark blue -> teal -> yellow
145 img.data[o] = Math.round(255 * Math.min(1, Math.max(0, 1.8 * z - 0.6)));
146 img.data[o + 1] = Math.round(255 * Math.pow(z, 0.9));
147 img.data[o + 2] = Math.round(255 * Math.max(0, 0.55 - 0.5 * z + 0.3 * Math.sin(Math.PI * z)));
148 img.data[o + 3] = 255;
149 }
150 }
151 // putImageData ignores the transform, so go through a canvas and drawImage
152 const tmp = document.createElement("canvas"); tmp.width = iw; tmp.height = ih;
153 tmp.getContext("2d")!.putImageData(img, 0, 0);
154 ctx.imageSmoothingEnabled = false;
155 ctx.drawImage(tmp, padL, padT, iw, ih);
156 ctx.font = "11px system-ui, sans-serif"; ctx.fillStyle = css("--muted");
157 for (const f of logTicks(fmin, fmax)) {
158 const y = padT + ih * (1 - Math.log(f / fmin) / Math.log(fmax / fmin));
159 ctx.textAlign = "right"; ctx.fillText(fmt(f), padL - 4, y + 4);
160 }
161 const dur = (frames.length * hop) / fs;
162 for (const t of niceTicks(0, dur, 6)) { ctx.textAlign = "center"; ctx.fillText(`${t}s`, padL + (iw * t) / dur, h - 4); }
163 if (opts.title) { ctx.fillStyle = "#fff"; ctx.textAlign = "left"; ctx.fillText(opts.title, padL + 6, padT + 13); }
164}