/ interactive_tutorials / hardening_softening
Sign in
interactive_tutorials / hardening_softening
hardening_softening / app / js / phase-page.js
622 lines · 21.8 KBBlameHistoryRaw
1// The phase-space slide: orbits of the oscillator in the (x, x') plane, with
2// x' = p/m (see orbits.js for which orbits), computed in a worker whenever the
3// parameters change. The orbits show the structure of the phase plane; they
4// all keep one style. Playing means the sound (as on the other slides, normalized to the orbit's largest
5// |x|) and a point running along it with a fading tail, at 1/100 x or real
6// time. Stop, or changing a parameter, stops it. Clicking any point of the
7// plot, on an orbit or not, adds the orbit from that point and plays it from
8// there (on an existing orbit, the same curve); for a driven system it
9// starts at drive phase 0, and the path to its settled motion is drawn
10// faintly. Added orbits are marked at their start and kept (the last
11// MAX_ADDED) until a parameter changes.
12//
13// controls: the element for the presets dropdown and sliders. container: the
14// element for the plot and its buttons. params: initial slider values (see
15// controls.js; no x0, since each orbit has its own start). sliders: per-slider
16// overrides. presets: [{ name, group?, params }]. instruments: also offer
17// instruments, fixed linear filters applied to the sound (instruments.js),
18// with a dry / wet mix and loudness normalization, and optionally a notch
19// (NOTCH_Q) removing the driving frequency first; tuned ones follow the
20// current |f0| (220 Hz when f0 = 0). An optional live spectrogram shows what
21// is heard (before the volume); while it shows, the plot is shorter.
23import { color, DRAW_SCALE, prepare } from './canvas.js';
24import { bindSliders, createPresetSelect, physicsOf, sliderSpecs, slidersHTML, volumeHTML } from './controls.js';
25import { amplitude, omegaBound, step, X_MAX } from './duffing.js';
26import { computeOrbitFrom, computeOrbits } from './orbits.js';
27import { createInstrumentChain } from './instrument-chain.js';
28import { DEFAULT_SCALE, impulseResponse, INSTRUMENTS, SCALES } from './instruments.js';
29import { createSound } from './sound.js';
30import { createSpectrogram, SPEC_FFT } from './spectrogram.js';
32const SPEEDS = [{ label: '1/100×', value: 0.01 }, { label: 'real time', value: 1 }];
33const TAIL_SECONDS = 0.5; // on screen
34const MAX_TAIL = 6000;
35const MAX_ADDED = 8;
36const NOTCH_Q = 30; // the drive notch: about (Omega / 2 pi) / NOTCH_Q wide
38// round steps for axis ticks
39function tickStep(range) {
40 const raw = range / 4;
41 const mag = 10 ** Math.floor(Math.log10(raw));
42 return [1, 2, 2.5, 5, 10].map((m) => m * mag).find((s) => s >= raw);
45// A worker running orbits-worker.js. A sandboxed page (one served with an
46// opaque origin, as on the vault's sites) may not start a worker from its own
47// URL, nor any module worker; so there, fetch the worker's modules and run
48// them as one classic script (see classicWorker). If that fails too, compute
49// on the main thread, through the same messages. Messages posted while the
50// worker is being set up wait for it.
51function createOrbitsWorker() {
52 if (self.origin !== 'null') {
53 try {
54 return new Worker(new URL('./orbits-worker.js', import.meta.url), { type: 'module' });
55 } catch {
56 // fall through
57 }
58 }
59 const proxy = {
60 onmessage: null,
61 queue: [],
62 target: null,
63 stopped: false,
64 postMessage(m) {
65 if (this.target) this.target.postMessage(m);
66 else this.queue.push(m);
67 },
68 terminate() {
69 this.stopped = true;
70 this.target?.terminate();
71 },
72 };
73 const attach = (target) => {
74 proxy.target = target;
75 target.onmessage = (e) => proxy.onmessage?.(e);
76 if (proxy.stopped) target.terminate();
77 else proxy.queue.splice(0).forEach((m) => target.postMessage(m));
78 };
79 classicWorker(['./duffing.js', './orbits.js', './orbits-worker.js'])
80 .then(attach)
81 .catch(() => attach(mainThreadWorker()));
82 return proxy;
85// A classic worker running these modules (relative to this file, in order),
86// each in its own scope: its imports read from the modules before it, and its
87// exports (export const / function) are collected for the ones after.
88async function classicWorker(paths) {
89 const sources = await Promise.all(paths.map((path) => fetch(new URL(path, import.meta.url)).then((r) => {
90 if (!r.ok) throw new Error(`${path}: ${r.status}`);
91 return r.text();
92 })));
93 const code = sources.map((src, i) => {
94 const names = [];
95 const body = src
96 .replace(/^import \{([^}]*)\} from '([^']+)';$/gm, (m, list, from) => `const {${list}} = __modules[${JSON.stringify(from)}];`)
97 .replace(/^export (const|function|let) (\w+)/gm, (m, kind, name) => {
98 names.push(name);
99 return `${kind} ${name}`;
100 });
101 return `__modules[${JSON.stringify(paths[i])}] = (() => {\n${body}\nreturn { ${names.join(', ')} };\n})();`;
102 }).join('\n');
103 const url = URL.createObjectURL(new Blob([`const __modules = {};\n${code}`], { type: 'text/javascript' }));
104 return new Worker(url);
107// the worker's job on the main thread, through the same messages
108function mainThreadWorker() {
109 const w = {
110 onmessage: null,
111 postMessage({ id, p, from }) {
112 setTimeout(() => {
113 const data = from ? { id, orbit: computeOrbitFrom(p, from) } : { id, ...computeOrbits(p) };
114 w.onmessage?.({ data });
115 }, 0);
116 },
117 terminate() { w.onmessage = null; },
118 };
119 return w;
122export function createPhasePage({ controls, container, params, sliders = {}, presets, instruments = false }) {
123 const { names, spec } = sliderSpecs(params, sliders);
124 const instrumentOptions = Object.entries(INSTRUMENTS).map(([key, { label }]) => `<option value="${key}">${label}</option>`).join('');
125 controls.innerHTML = `<div class="presets" data-presets></div>${slidersHTML(names, spec)}${instruments ? `
126 <div class="instrument-controls">
127 <label class="preset">Filter <select data-role="instrument">${instrumentOptions}</select></label>
128 <label class="preset">Scale <select data-role="scale">${Object.entries(SCALES).map(([key, { label }]) => `<option value="${key}">${label}</option>`).join('')}</select></label>
129 <div class="sliders">
130 <label class="row"><span>Dry / wet</span>
131 <input data-role="wet" type="range" min="0" max="1" step="0.01">
132 <output data-role="wet-value"></output>
133 </label>
134 </div>
135 <label class="check"><input data-role="normalize" type="checkbox"> Normalize loudness</label>
136 <label class="check"><input data-role="notch" type="checkbox"> Remove the driving frequency</label>
137 </div>` : ''}`;
138 container.innerHTML = `
139 <div class="stage">
140 <canvas class="phase"></canvas>
141 <div class="run-controls">
142 <button class="run" data-role="speed" title="Speed of the point along the orbit">Speed: ${SPEEDS[0].label}</button>
143 <button class="run" data-role="stop" disabled>&#9632; Stop</button>
144 ${volumeHTML()}
145 </div>
146 </div>
147 <div class="demo-footer">
148 <span class="caption">Click any point to start an orbit there and play it.</span>
149 <button class="link" data-role="spectrogram-toggle">Show spectrogram</button>
150 </div>
151 <canvas class="spectrogram" hidden></canvas>`;
152 const canvas = container.querySelector('canvas.phase');
153 const role = (name) => container.querySelector(`[data-role="${name}"]`);
154 const speedButton = role('speed');
155 const stopButton = role('stop');
157 let p = physicsOf(params);
158 let result = null; // { orbits, xmax, vmax }
159 let computing = false;
160 let playing = -1;
161 let speed = 0; // index into SPEEDS
162 let view = null; // the mapping used by the last draw, for hovering
164 // --- the sound and the point along the orbit
166 let playParams = null;
168 // the instrument the sound drives (when offered), live while playing
169 const inst = { name: 'raw', scale: DEFAULT_SCALE, wet: 0.95, normalize: true, notch: false };
170 // the notch before the instrument: on only with a drive; otherwise an all-pass
171 // (which leaves every frequency's level alone)
172 let notch = null;
173 const setNotch = () => {
174 if (!notch) return;
175 const on = inst.notch && p.F > 0 && p.Omega > 0;
176 notch.type = on ? 'notch' : 'allpass';
177 notch.frequency.value = on ? p.Omega / (2 * Math.PI) : 1000;
178 };
179 let chain = null;
180 const instrumentSettings = () => ({ name: inst.name, base: Math.abs(params.freq) || 220, scale: inst.scale, wet: inst.wet });
181 if (instruments) {
182 const q = (r) => controls.querySelector(`[data-role="${r}"]`);
183 const select = q('instrument');
184 const wetInput = q('wet');
185 const wetOutput = q('wet-value');
186 const normalize = q('normalize');
187 normalize.checked = inst.normalize;
188 const notchBox = q('notch');
189 notchBox.checked = inst.notch;
190 notchBox.addEventListener('change', () => {
191 inst.notch = notchBox.checked;
192 setNotch();
193 });
194 normalize.addEventListener('change', () => {
195 inst.normalize = normalize.checked;
196 chain?.setNormalize(inst.normalize);
197 });
198 const scaleSelect = q('scale');
199 // the scale applies to the marimba and harp only
200 const showScale = () => { scaleSelect.disabled = !INSTRUMENTS[inst.name].usesScale; };
201 select.value = inst.name;
202 scaleSelect.value = inst.scale;
203 showScale();
204 wetInput.value = inst.wet;
205 wetOutput.textContent = inst.wet.toFixed(2);
206 select.addEventListener('change', () => {
207 inst.name = select.value;
208 showScale();
209 chain?.set(instrumentSettings());
210 });
211 scaleSelect.addEventListener('change', () => {
212 inst.scale = scaleSelect.value;
213 chain?.set(instrumentSettings());
214 });
215 wetInput.addEventListener('input', () => {
216 inst.wet = Number(wetInput.value);
217 wetOutput.textContent = inst.wet.toFixed(2);
218 chain?.setWet(inst.wet);
219 });
220 }
221 // the live spectrogram: of the instrument when there is one, else of the oscillator
222 const specCanvas = container.querySelector('canvas.spectrogram');
223 const spectrogram = createSpectrogram(specCanvas);
224 const specToggle = role('spectrogram-toggle');
225 specToggle.addEventListener('click', () => {
226 specCanvas.hidden = !specCanvas.hidden;
227 container.classList.toggle('with-spectrogram', !specCanvas.hidden);
228 specToggle.textContent = specCanvas.hidden ? 'Show spectrogram' : 'Hide spectrogram';
229 draw();
230 spectrogram.draw();
231 });
233 const route = instruments
234 ? async (ctx, osc) => {
235 chain = await createInstrumentChain(ctx, impulseResponse);
236 notch = ctx.createBiquadFilter();
237 notch.Q.value = NOTCH_Q;
238 setNotch();
239 osc.connect(notch).connect(chain.input);
240 chain.set(instrumentSettings());
241 chain.setNormalize(inst.normalize);
242 const analyser = ctx.createAnalyser();
243 analyser.fftSize = SPEC_FFT;
244 analyser.smoothingTimeConstant = 0;
245 chain.output.connect(analyser);
246 spectrogram.attach(analyser);
247 return chain.output;
248 }
249 : null;
250 const sound = createSound({
251 volume: role('volume'),
252 params: () => playParams,
253 route,
254 fftSize: instruments ? 0 : SPEC_FFT,
255 onPlay: (analyser) => { if (analyser) spectrogram.attach(analyser); },
256 onStop: () => {
257 chain = null;
258 notch = null;
259 spectrogram.detach();
260 },
261 });
262 let trace = null; // { s, t, tail: [t, x, v, ...] }
263 let rafId = null;
264 let lastFrame = null;
266 function stopPlaying() {
267 playing = -1;
268 trace = null;
269 cancelAnimationFrame(rafId);
270 sound.stop();
271 stopButton.disabled = true;
272 draw();
273 }
275 function play(i) {
276 const o = result.orbits[i];
277 playing = i;
278 playParams = { ...p, x0: o.start.x, ref: o.ref };
279 sound.play({ ...o.start });
280 trace = { s: { ...o.start, escaped: false }, t: 0, tail: [0, o.start.x, o.start.v] };
281 stopButton.disabled = false;
282 lastFrame = null;
283 cancelAnimationFrame(rafId);
284 rafId = requestAnimationFrame(frame);
285 }
287 function frame(now) {
288 if (!trace) return;
289 if (lastFrame !== null && !trace.s.escaped) {
290 const dt = Math.min((now - lastFrame) / 1000, 0.05) * SPEEDS[speed].value;
291 // record about 40 points per oscillation
292 const w = Math.max(omegaBound(p, 0.5), p.F ? p.Omega : 0, 2 * Math.PI);
293 const n = Math.min(4000, Math.max(1, Math.ceil(dt / ((2 * Math.PI) / (w * 40)))));
294 const { s } = trace;
295 for (let i = 0; i < n && !s.escaped; i++) {
296 step(p, s, dt / n, omegaBound(p, Math.min(X_MAX, 1.2 * Math.max(amplitude(p, s.x, s.v), Math.abs(s.x)))));
297 trace.t += dt / n;
298 trace.tail.push(trace.t, s.x, s.v);
299 }
300 const keep = TAIL_SECONDS * SPEEDS[speed].value;
301 let cut = 0;
302 while (cut < trace.tail.length - 3 && (trace.tail[cut] < trace.t - keep || trace.tail.length - cut > 3 * MAX_TAIL)) cut += 3;
303 if (cut) trace.tail.splice(0, cut);
304 }
305 lastFrame = now;
306 draw();
307 rafId = requestAnimationFrame(frame);
308 }
310 speedButton.addEventListener('click', () => {
311 speed = (speed + 1) % SPEEDS.length;
312 speedButton.textContent = `Speed: ${SPEEDS[speed].label}`;
313 if (trace) trace.tail = trace.tail.slice(-3);
314 });
315 stopButton.addEventListener('click', stopPlaying);
317 // --- computing the orbits, in a worker; a new request replaces a running one
319 let worker = null;
320 let busy = false;
321 let requestId = 0;
322 let timer = null;
324 function compute() {
325 if (busy) {
326 worker.terminate();
327 worker = null;
328 }
329 if (!worker) {
330 worker = createOrbitsWorker();
331 worker.onmessage = (e) => {
332 if (e.data.id !== requestId) return;
333 busy = false;
334 computing = false;
335 result = e.data;
336 draw();
337 };
338 }
339 busy = true;
340 computing = true;
341 requestId++;
342 worker.postMessage({ id: requestId, p });
343 draw();
344 }
346 // the orbit from a clicked point, in a second worker, so the full set keeps
347 // its own; a new click replaces a pending one
348 let oneWorker = null;
349 let oneBusy = false;
350 let oneId = 0;
351 let pendingPoint = null; // { x, v } being computed
353 function cancelAdded() {
354 if (oneBusy) {
355 oneWorker.terminate();
356 oneWorker = null;
357 oneBusy = false;
358 }
359 oneId++;
360 pendingPoint = null;
361 }
363 function addOrbitFrom(point) {
364 stopPlaying();
365 cancelAdded();
366 if (!oneWorker) {
367 oneWorker = createOrbitsWorker();
368 oneWorker.onmessage = (e) => {
369 if (e.data.id !== oneId || !result) return;
370 oneBusy = false;
371 pendingPoint = null;
372 const added = result.orbits.filter((o) => o.added);
373 if (added.length >= MAX_ADDED) result.orbits.splice(result.orbits.indexOf(added[0]), 1);
374 result.orbits.push({ ...e.data.orbit, added: true });
375 play(result.orbits.length - 1);
376 };
377 }
378 oneBusy = true;
379 pendingPoint = point;
380 oneWorker.postMessage({ id: oneId, p, from: point });
381 draw();
382 }
384 function changed() {
385 cancelAdded();
386 stopPlaying();
387 p = physicsOf(params);
388 computing = true;
389 clearTimeout(timer);
390 timer = setTimeout(compute, 100);
391 draw();
392 }
394 let presetSelect = null;
395 const sliderControls = bindSliders({
396 root: controls,
397 names,
398 spec,
399 params,
400 onInput: () => {
401 presetSelect?.markCustom();
402 changed();
403 },
404 });
405 presetSelect = createPresetSelect({
406 container: controls.querySelector('[data-presets]'),
407 presets,
408 params,
409 names,
410 onChoose: () => {
411 sliderControls.showAll();
412 changed();
413 },
414 });
416 // --- drawing
418 function draw() {
419 if (!canvas.clientWidth) return;
420 const { ctx, w, h } = prepare(canvas);
421 const fg = color('--fg');
422 const left = 64;
423 const right = 14;
424 const top = 40; // below the buttons
425 const bottom = 36;
426 const pw = w - left - right;
427 const ph = h - top - bottom;
429 // axes: symmetric, fitted to the orbits; escaping paths do not set x'
430 const orbits = result?.orbits ?? [];
431 let xmax = result?.xmax ?? 0.5;
432 for (const o of orbits) {
433 if (!o.added) continue;
434 for (const arr of [o.pts, o.path ?? []]) for (let i = 0; i < arr.length; i += 2) xmax = Math.max(xmax, Math.abs(arr[i]));
435 }
436 const xr = 1.08 * Math.max(Math.min(xmax, X_MAX), 0.05);
437 let vmax = 0;
438 for (const o of orbits) {
439 if (o.kind === 'escape') continue;
440 for (let i = 1; i < o.pts.length; i += 2) vmax = Math.max(vmax, Math.abs(o.pts[i]));
441 }
442 if (!vmax) vmax = result?.vmax || 1;
443 const vr = 1.08 * vmax;
444 const X = (x) => left + ((x + xr) / (2 * xr)) * pw;
445 const Y = (v) => top + ph / 2 - (v / vr) * (ph / 2);
446 view = { X, Y, left, top, pw, ph, xr, vr };
448 ctx.font = '13px "Hanken Grotesk", system-ui, sans-serif';
449 ctx.strokeStyle = fg;
450 ctx.fillStyle = fg;
451 ctx.lineWidth = 1;
452 ctx.strokeRect(left, top, pw, ph);
453 ctx.globalAlpha = 0.25;
454 ctx.beginPath();
455 ctx.moveTo(X(0), top);
456 ctx.lineTo(X(0), top + ph);
457 ctx.moveTo(left, Y(0));
458 ctx.lineTo(left + pw, Y(0));
459 ctx.stroke();
460 ctx.globalAlpha = 1;
461 // ticks
462 ctx.textAlign = 'center';
463 ctx.textBaseline = 'top';
464 const xs = tickStep(2 * xr);
465 for (let x = -Math.floor(xr / xs) * xs; x <= xr + 1e-9; x += xs) {
466 ctx.beginPath();
467 ctx.moveTo(X(x), top + ph);
468 ctx.lineTo(X(x), top + ph + 4);
469 ctx.stroke();
470 ctx.fillText(Math.abs(x) < 1e-9 ? '0' : x.toFixed(2).replace(/0$/, ''), X(x), top + ph + 6);
471 }
472 ctx.textAlign = 'right';
473 ctx.textBaseline = 'middle';
474 const vs = tickStep(2 * vr);
475 for (let v = -Math.floor(vr / vs) * vs; v <= vr + 1e-9; v += vs) {
476 ctx.beginPath();
477 ctx.moveTo(left - 4, Y(v));
478 ctx.lineTo(left, Y(v));
479 ctx.stroke();
480 ctx.fillText(Math.abs(v) < 1e-9 ? '0' : String(Math.round(v)), left - 6, Y(v));
481 }
482 ctx.font = 'italic 17px Georgia, serif';
483 ctx.textAlign = 'right';
484 ctx.textBaseline = 'bottom';
485 ctx.fillText('x', left + pw - 4, Y(0) - 4);
486 ctx.textAlign = 'left';
487 ctx.textBaseline = 'top';
488 ctx.fillText('ẋ = p/m', X(0) + 6, top + 4);
490 // orbits, clipped to the plot
491 ctx.save();
492 ctx.beginPath();
493 ctx.rect(left, top, pw, ph);
494 ctx.clip();
495 const accent = color('--accent');
496 const force = color('--force');
497 // a playing added driven orbit's path from the clicked point to its
498 // settled motion, faint (only while it plays, or the paths would bury the
499 // plot)
500 if (playing >= 0 && orbits[playing]?.path) {
501 ctx.globalAlpha = 0.35;
502 ctx.lineWidth = 0.8;
503 ctx.strokeStyle = accent;
504 polyline(ctx, orbits[playing].path, X, Y);
505 }
506 orbits.forEach((o) => {
507 ctx.globalAlpha = o.kind === 'irregular' ? 0.5 : 0.85;
508 ctx.lineWidth = o.kind === 'irregular' ? 0.5 : 1.2;
509 ctx.strokeStyle = o.kind === 'escape' ? force : accent;
510 polyline(ctx, o.pts, X, Y);
511 });
512 // where each added orbit starts, and a click still being computed
513 ctx.globalAlpha = 1;
514 ctx.lineWidth = 1.5;
515 orbits.forEach((o) => {
516 if (!o.added) return;
517 ctx.strokeStyle = o.kind === 'escape' ? force : accent;
518 ctx.beginPath();
519 ctx.arc(X(o.start.x), Y(o.start.v), 4, 0, 2 * Math.PI);
520 ctx.stroke();
521 });
522 if (pendingPoint) {
523 ctx.strokeStyle = fg;
524 ctx.beginPath();
525 ctx.arc(X(pendingPoint.x), Y(pendingPoint.v), 4, 0, 2 * Math.PI);
526 ctx.stroke();
527 }
528 // the point along the playing orbit, with its fading tail
529 if (trace) {
530 const tail = trace.tail;
531 const orange = color('--brand-orange');
532 ctx.strokeStyle = orange;
533 ctx.lineWidth = 2.5;
534 const keep = TAIL_SECONDS * SPEEDS[speed].value;
535 const segs = 24;
536 for (let k = 0; k < segs; k++) {
537 // the tail in segs pieces, older ones fainter
538 const t0 = trace.t - keep * (1 - k / segs);
539 const t1 = trace.t - keep * (1 - (k + 1) / segs);
540 ctx.globalAlpha = (k + 1) / segs;
541 ctx.beginPath();
542 let started = false;
543 for (let j = 0; j < tail.length; j += 3) {
544 if (tail[j] < t0 || tail[j] > t1 + 1e-12) continue;
545 if (!started) {
546 // start from the previous point, so the pieces join up
547 const k0 = Math.max(0, j - 3);
548 ctx.moveTo(X(tail[k0 + 1]), Y(tail[k0 + 2]));
549 started = true;
550 }
551 ctx.lineTo(X(tail[j + 1]), Y(tail[j + 2]));
552 }
553 ctx.stroke();
554 }
555 ctx.globalAlpha = 1;
556 if (!trace.s.escaped) {
557 ctx.fillStyle = orange;
558 ctx.beginPath();
559 ctx.arc(X(trace.s.x), Y(trace.s.v), 5, 0, 2 * Math.PI);
560 ctx.fill();
561 }
562 }
563 ctx.restore();
564 ctx.globalAlpha = 1;
566 if (computing || pendingPoint) {
567 ctx.fillStyle = fg;
568 ctx.globalAlpha = 0.6;
569 ctx.font = '15px "Hanken Grotesk", system-ui, sans-serif';
570 ctx.textAlign = 'left';
571 ctx.textBaseline = 'top';
572 ctx.fillText(computing ? 'Computing orbits\u2026' : 'Computing the orbit\u2026', left + 8, top + 8);
573 ctx.globalAlpha = 1;
574 }
575 }
577 function polyline(ctx, pts, X, Y) {
578 ctx.beginPath();
579 ctx.moveTo(X(pts[0]), Y(pts[1]));
580 for (let i = 2; i < pts.length; i += 2) ctx.lineTo(X(pts[i]), Y(pts[i + 1]));
581 ctx.stroke();
582 }
584 // --- hovering and clicking
586 // the pointer in drawing units
587 function pointer(e) {
588 const rect = canvas.getBoundingClientRect();
589 const scale = canvas.clientWidth / rect.width / DRAW_SCALE; // client pixels to drawing units
590 return [(e.clientX - rect.left) * scale, (e.clientY - rect.top) * scale];
591 }
593 // the point of the plane under the pointer, { x, v }, or null outside the plot
594 function pointAt(e) {
595 if (!view) return null;
596 const [mx, my] = pointer(e);
597 const { left, top, pw, ph, xr, vr } = view;
598 if (mx < left || mx > left + pw || my < top || my > top + ph) return null;
599 const x = ((mx - left) / pw) * 2 * xr - xr;
600 const v = ((top + ph / 2 - my) / (ph / 2)) * vr;
601 return Math.abs(x) < X_MAX ? { x, v } : null;
602 }
604 canvas.addEventListener('mousemove', (e) => {
605 canvas.style.cursor = pointAt(e) ? 'crosshair' : '';
606 });
607 // a click anywhere in the plot starts the orbit from that point
608 canvas.addEventListener('click', (e) => {
609 const point = pointAt(e);
610 if (point) addOrbitFrom(point);
611 });
613 compute();
615 return {
616 draw: () => {
617 draw();
618 spectrogram.draw();
619 },
620 pause: stopPlaying,
621 };
↑↓ move↵openescclose