7212d95Hardening and softening tutorialJeremy Magland 1// Plots of the instruments' frequency responses |H(f)| (instruments.js), one
2// small panel each, in dB against frequency on a log scale.
4import { color, prepare } from './canvas.js';
5import { INSTRUMENTS, responseMagnitude } from './instruments.js';
7const F_MIN = 50;
8const F_MAX = 4000;
9const DB_MIN = -40;
10const POINTS = 1500;
12// names: the instruments to plot; base: the tuning (Hz) for tuned ones.
13// Returns a sim for deck.js: { draw, pause }.
14export function createResponsePlot(canvas, { names, base = 220 }) {
15 const fs = Array.from({ length: POINTS }, (_, i) => F_MIN * (F_MAX / F_MIN) ** (i / (POINTS - 1)));
16 const curves = names.map((name) => responseMagnitude(name, base, fs).map((m) => Math.max(DB_MIN, 20 * Math.log10(m + 1e-12))));
18 function draw() {
19 if (!canvas.clientWidth) return;
20 const { ctx, w, h } = prepare(canvas);
21 const fg = color('--fg');
22 const accent = color('--accent');
23 const left = 118;
24 const right = 8;
25 const bottom = 26;
26 const gap = 8;
27 const ph = (h - bottom - gap * (names.length - 1)) / names.length;
28 const pw = w - left - right;
29 const X = (f) => left + (Math.log(f / F_MIN) / Math.log(F_MAX / F_MIN)) * pw;
30 ctx.font = '12px "Hanken Grotesk", system-ui, sans-serif';
31 names.forEach((name, k) => {
32 const top = k * (ph + gap);
33 const Y = (db) => top + (db / DB_MIN) * ph;
34 ctx.strokeStyle = fg;
35 ctx.lineWidth = 1;
36 ctx.globalAlpha = 0.2;
37 for (const f of [100, 200, 500, 1000, 2000]) {
38 ctx.beginPath();
39 ctx.moveTo(X(f), top);
40 ctx.lineTo(X(f), top + ph);
41 ctx.stroke();
42 }
43 ctx.globalAlpha = 1;
44 ctx.strokeRect(left, top, pw, ph);
45 ctx.fillStyle = fg;
46 ctx.textAlign = 'right';
47 ctx.textBaseline = 'middle';
48 ctx.fillText(INSTRUMENTS[name].label.replace(/ \(.*\)$/, ''), left - 8, top + ph / 2);
49 ctx.strokeStyle = accent;
50 ctx.lineWidth = 1.2;
51 ctx.beginPath();
52 curves[k].forEach((db, i) => (i ? ctx.lineTo(X(fs[i]), Y(db)) : ctx.moveTo(X(fs[i]), Y(db))));
53 ctx.stroke();
54 });
55 // frequency axis
56 ctx.fillStyle = fg;
57 ctx.textAlign = 'center';
58 ctx.textBaseline = 'top';
59 const yAxis = h - bottom + 4;
60 for (const f of [50, 100, 200, 500, 1000, 2000, 4000]) ctx.fillText(f >= 1000 ? `${f / 1000} kHz` : `${f} Hz`, X(f), yAxis);
61 }
63 return { draw, pause: () => {} };
64}