51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 1// Mass on a frictionless spring. Positions are in units of the maximum
2// swing drawn on screen, so q lies in [-1, 1].
4function color(name) {
5 return getComputedStyle(document.documentElement).getPropertyValue(name).trim();
6}
8// Size a canvas for the device pixel ratio and return its context and CSS size.
9function prepare(canvas) {
10 const ctx = canvas.getContext('2d');
11 const dpr = window.devicePixelRatio || 1;
12 const w = canvas.clientWidth;
13 const h = canvas.clientHeight;
14 if (canvas.width !== w * dpr || canvas.height !== h * dpr) {
15 canvas.width = w * dpr;
16 canvas.height = h * dpr;
17 }
18 ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
19 ctx.clearRect(0, 0, w, h);
20 return { ctx, w, h };
21}
23// Horizontal layout shared by the spring diagram, the q0 slider and the phase plot,
24// so that a given q sits at the same x on all of them.
25function layout(w) {
26 const rest = w * 0.5;
27 const swing = Math.min(w * 0.3, 200);
28 return { rest, swing, qToX: (q) => rest + q * swing };
29}
31// params: { k, m, q0 }, read live so sliders can change them.
32// labels: which of 'm', 'k', 'q', 'F', 'p', 'q0' to draw.
33// pScale: length of the p arrow per unit momentum, as a fraction of the swing;
34// by default the arrow peaks at the same length as q.
35function createSpring({ canvas, button, params, labels = [], speed = 1, pScale, onDraw = () => {} }) {
36 let q = params.q0;
37 let p = 0;
39 function step(dt) {
40 // velocity Verlet on dq/dt = p/m, dp/dt = -k q
41 const { k, m } = params;
42 const f = -k * q;
43 q += (p / m) * dt + (0.5 * f / m) * dt * dt;
44 p += 0.5 * (f - k * q) * dt;
45 }
47 function draw() {
48 if (!canvas.clientWidth) return;
49 const { ctx, w, h } = prepare(canvas);
51 const fg = color('--fg');
52 const accent = color('--accent');
53 const { rest, swing, qToX } = layout(w);
54 const wallX = 20;
55 const floorY = h * 0.62;
56 const box = 50;
57 const center = qToX(q);
58 const boxX = center - box / 2;
59 const springY = floorY - box / 2;
61 // wall and floor
62 ctx.strokeStyle = fg;
63 ctx.lineWidth = 2;
64 ctx.beginPath();
65 ctx.moveTo(wallX, floorY - box * 1.6);
66 ctx.lineTo(wallX, floorY);
67 ctx.lineTo(w - 10, floorY);
68 ctx.stroke();
70 // spring (zig-zag)
71 const coils = 12;
72 const amp = 10;
73 const start = wallX;
74 const end = boxX;
75 const lead = 12;
76 ctx.lineWidth = 1.5;
77 ctx.beginPath();
78 ctx.moveTo(start, springY);
79 ctx.lineTo(start + lead, springY);
80 const len = end - start - 2 * lead;
81 for (let i = 0; i < coils; i++) {
82 const sx = start + lead + ((i + 0.5) / coils) * len;
83 ctx.lineTo(sx, springY + (i % 2 ? amp : -amp));
84 }
85 ctx.lineTo(end - lead, springY);
86 ctx.lineTo(end, springY);
87 ctx.stroke();
89 // mass
90 ctx.fillStyle = accent;
91 ctx.fillRect(boxX, floorY - box, box, box);
93 // rest position marker
94 ctx.strokeStyle = fg;
95 ctx.globalAlpha = 0.3;
96 ctx.setLineDash([4, 4]);
97 ctx.beginPath();
98 ctx.moveTo(rest, floorY - box * 1.4);
99 ctx.lineTo(rest, floorY + 34);
100 ctx.stroke();
101 ctx.setLineDash([]);
102 ctx.globalAlpha = 1;
104 onDraw(q, p);
106 if (!labels.length) return;
108 ctx.font = 'italic 18px Georgia, serif';
109 ctx.textAlign = 'center';
111 if (labels.includes('m')) {
112 ctx.fillStyle = color('--bg');
113 ctx.textBaseline = 'middle';
114 ctx.fillText('m', center, floorY - box / 2);
115 }
116 if (labels.includes('k')) {
117 ctx.fillStyle = fg;
118 ctx.textBaseline = 'bottom';
119 ctx.fillText('k', (start + end) / 2, springY - amp - 4);
120 }
121 if (labels.includes('q0')) {
122 // where the block was let go from
123 const x0 = qToX(params.q0);
124 ctx.strokeStyle = fg;
125 ctx.globalAlpha = 0.5;
126 ctx.setLineDash([2, 3]);
127 ctx.beginPath();
128 ctx.moveTo(x0, floorY - box - 34);
129 ctx.lineTo(x0, floorY);
130 ctx.stroke();
131 ctx.setLineDash([]);
132 ctx.globalAlpha = 1;
133 ctx.fillStyle = fg;
134 ctx.textBaseline = 'bottom';
135 ctx.fillText('q₀', x0, floorY - box - 36);
136 }
138 // q below the floor; F and p above the block
139 const { k, m } = params;
140 const pLen = (pScale ?? 1 / Math.sqrt(k * m)) * swing;
141 if (labels.includes('q')) arrow(ctx, rest, center, floorY + 22, fg, 'q', 'below');
142 if (labels.includes('F')) arrow(ctx, center, center - q * swing, floorY - box - 40, color('--force'), 'F', 'above');
143 if (labels.includes('p')) arrow(ctx, center, center + p * pLen, floorY - box - 14, color('--momentum'), 'p', 'above');
144 }
146 function setLabels(value) {
147 labels = value;
148 draw();
149 }
151 const loop = createLoop({ button, step, draw, speed });
153 // Back to being held at q0, at rest.
154 function reset() {
155 q = params.q0;
156 p = 0;
157 loop.reset();
158 }
160 return { draw, setLabels, reset, pause: loop.pause };
161}
163// Animation driven by a Start / Stop / Continue button.
164function createLoop({ button, step, draw, speed = 1 }) {
165 let running = false;
166 let lastTime = null;
167 let rafId = null;
169 function frame(t) {
170 if (!running) return;
171 if (lastTime !== null) {
172 const dt = speed * Math.min((t - lastTime) / 1000, 0.05);
173 const n = 4;
174 for (let i = 0; i < n; i++) step(dt / n);
175 }
176 lastTime = t;
177 draw();
178 rafId = requestAnimationFrame(frame);
179 }
181 function setRunning(value) {
182 running = value;
183 cancelAnimationFrame(rafId);
184 if (running) {
185 lastTime = null;
186 rafId = requestAnimationFrame(frame);
187 }
188 if (running || button.textContent !== 'Start') {
189 button.textContent = running ? 'Stop' : 'Continue';
190 }
191 }
193 button.addEventListener('click', () => setRunning(!running));
194 window.addEventListener('resize', draw);
196 return {
197 pause: () => running && setRunning(false),
198 reset: () => {
199 setRunning(false);
200 button.textContent = 'Start';
201 draw();
202 },
203 };
204}
206// Pendulum: a bob of mass m on a massless rod of length L, angle theta from
207// straight down, kept in [-pi, pi].
208// params: { m, L, g, theta0, p0 }, read live so sliders can change them.
209// labels: which of 'm', 'L', 'theta', 'p', 'g' to draw.
210// centered: put the pivot mid-canvas so the bob can go over the top; the rod
211// is then drawn to scale, with L = 1.5 filling the canvas.
212// pScale: length of the p arrow in px per unit momentum; by default the arrow
213// peaks at 70px when let go from theta0 at rest.
214function createPendulum({ canvas, button, params, labels = [], centered = false, pScale, onDraw = () => {} }) {
215 let theta = params.theta0;
216 let p = params.p0;
218 function step(dt) {
219 // leapfrog on dtheta/dt = p / (m L^2), dp/dt = -m g L sin(theta)
220 const { m, L, g } = params;
221 p -= 0.5 * dt * m * g * L * Math.sin(theta);
222 theta += dt * p / (m * L * L);
223 p -= 0.5 * dt * m * g * L * Math.sin(theta);
224 if (theta > Math.PI) theta -= 2 * Math.PI;
225 if (theta < -Math.PI) theta += 2 * Math.PI;
226 }
228 function draw() {
229 if (!canvas.clientWidth) return;
230 const { ctx, w, h } = prepare(canvas);
231 const fg = color('--fg');
232 const accent = color('--accent');
233 const { m, L, g } = params;
234 const px = w / 2;
235 const py = centered ? h / 2 : 30;
236 const maxRod = centered ? h / 2 - 28 : Math.min(h - 80, w * 0.4);
237 const rod = centered ? maxRod * L / 1.5 : maxRod;
238 const bx = px + rod * Math.sin(theta);
239 const by = py + rod * Math.cos(theta);
240 const r = 18;
242 // ceiling (only when hanging from the top) and pivot
243 ctx.strokeStyle = fg;
244 ctx.lineWidth = 2;
245 if (!centered) {
246 ctx.beginPath();
247 ctx.moveTo(px - 50, py);
248 ctx.lineTo(px + 50, py);
249 ctx.stroke();
250 }
252 // vertical reference
253 ctx.globalAlpha = 0.3;
254 ctx.setLineDash([4, 4]);
255 ctx.beginPath();
256 ctx.moveTo(px, py);
257 ctx.lineTo(px, py + rod + r + 10);
258 ctx.stroke();
259 ctx.setLineDash([]);
260 ctx.globalAlpha = 1;
262 // rod and bob
263 ctx.lineWidth = 2;
264 ctx.beginPath();
265 ctx.moveTo(px, py);
266 ctx.lineTo(bx, by);
267 ctx.stroke();
268 ctx.fillStyle = fg;
269 ctx.beginPath();
270 ctx.arc(px, py, 4, 0, 2 * Math.PI);
271 ctx.fill();
272 ctx.fillStyle = accent;
273 ctx.beginPath();
274 ctx.arc(bx, by, r, 0, 2 * Math.PI);
275 ctx.fill();
277 onDraw(theta, p);
279 ctx.font = 'italic 18px Georgia, serif';
280 ctx.textAlign = 'center';
281 ctx.textBaseline = 'middle';
283 if (labels.includes('m')) {
284 ctx.fillStyle = color('--bg');
285 ctx.fillText('m', bx, by);
286 }
288 if (labels.includes('L')) {
289 // beside the middle of the rod, on the side away from the vertical
290 const side = theta >= 0 ? 1 : -1;
291 ctx.fillStyle = fg;
292 ctx.fillText('L', (px + bx) / 2 + side * 14 * Math.cos(theta), (py + by) / 2 - side * 14 * Math.sin(theta));
293 }
295 if (labels.includes('theta')) {
296 // arc from the vertical to the rod
297 const arcR = Math.min(44, rod * 0.6);
298 ctx.strokeStyle = fg;
299 ctx.fillStyle = fg;
300 ctx.lineWidth = 1.5;
301 ctx.beginPath();
302 ctx.arc(px, py, arcR, Math.PI / 2, Math.PI / 2 - theta, theta > 0);
303 ctx.stroke();
304 const mid = Math.PI / 2 - theta / 2;
305 ctx.fillText('θ', px + (arcR + 14) * Math.cos(mid), py + (arcR + 14) * Math.sin(mid));
306 }
308 if (labels.includes('p')) {
309 // along the direction of motion, perpendicular to the rod
310 const peak = Math.sqrt(2 * m * m * g * L * L * L * (1 - Math.cos(params.theta0)));
311 const len = p * (pScale ?? (peak ? 70 / peak : 0));
312 const tx = Math.cos(theta);
313 const ty = -Math.sin(theta);
314 const momentum = color('--momentum');
315 ctx.strokeStyle = momentum;
316 ctx.fillStyle = momentum;
317 ctx.lineWidth = 1.5;
318 ctx.beginPath();
319 ctx.moveTo(bx, by);
320 ctx.lineTo(bx + tx * len, by + ty * len);
321 ctx.stroke();
322 if (Math.abs(len) > 8) {
323 const d = Math.sign(len);
324 const ex = bx + tx * len;
325 const ey = by + ty * len;
326 ctx.beginPath();
327 ctx.moveTo(ex, ey);
328 ctx.lineTo(ex - d * 8 * tx - 4 * ty, ey - d * 8 * ty + 4 * tx);
329 ctx.lineTo(ex - d * 8 * tx + 4 * ty, ey - d * 8 * ty - 4 * tx);
330 ctx.closePath();
331 ctx.fill();
332 ctx.fillText('p', ex + d * 12 * tx, ey + d * 12 * ty);
333 }
334 }
336 if (labels.includes('g')) {
337 // gravity, pointing down, off to the side
338 const gx = Math.min(px + maxRod + 50, w - 20);
339 ctx.strokeStyle = fg;
340 ctx.fillStyle = fg;
341 ctx.lineWidth = 1.5;
342 ctx.beginPath();
343 ctx.moveTo(gx, py + 40);
344 ctx.lineTo(gx, py + 90);
345 ctx.stroke();
346 ctx.beginPath();
347 ctx.moveTo(gx, py + 90);
348 ctx.lineTo(gx - 4, py + 82);
349 ctx.lineTo(gx + 4, py + 82);
350 ctx.closePath();
351 ctx.fill();
352 ctx.fillText('g', gx + 14, py + 65);
353 }
354 }
356 const loop = createLoop({ button, step, draw });
358 function setLabels(value) {
359 labels = value;
360 draw();
361 }
363 // Back to the initial state, held still.
364 function reset() {
365 theta = params.theta0;
366 p = params.p0;
367 loop.reset();
368 }
370 return { draw, setLabels, reset, pause: loop.pause };
371}
373function arrow(ctx, from, to, y, col, label, side) {
374 const dir = Math.sign(to - from);
375 ctx.strokeStyle = col;
376 ctx.fillStyle = col;
377 ctx.lineWidth = 1.5;
378 ctx.beginPath();
379 ctx.moveTo(from, y);
380 ctx.lineTo(to, y);
381 ctx.stroke();
382 if (Math.abs(to - from) > 8) {
383 ctx.beginPath();
384 ctx.moveTo(to, y);
385 ctx.lineTo(to - dir * 8, y - 4);
386 ctx.lineTo(to - dir * 8, y + 4);
387 ctx.closePath();
388 ctx.fill();
389 }
390 ctx.textBaseline = side === 'above' ? 'bottom' : 'top';
391 ctx.fillText(label, (from + to) / 2, side === 'above' ? y - 4 : y + 4);
392}
394// Horizontal bars for kinetic, potential and total energy, scaled to the total.
395function drawEnergyBars(canvas, params, q, p) {
396 if (!canvas.clientWidth) return;
397 const { ctx, w } = prepare(canvas);
398 const { k, m, q0 } = params;
399 const kinetic = (p * p) / (2 * m);
400 const potential = 0.5 * k * q * q;
401 const total = 0.5 * k * q0 * q0;
403 const fg = color('--fg');
404 const kColor = color('--momentum');
405 const pColor = color('--potential');
406 const labelW = 90;
407 const barW = Math.min(w - labelW - 10, 400);
408 const left = Math.max(0, (w - labelW - barW) / 2);
409 const barX = left + labelW;
410 const rowH = 30;
411 const barH = 18;
413 ctx.font = '15px system-ui, sans-serif';
414 ctx.textBaseline = 'middle';
415 ctx.textAlign = 'right';
417 const rows = [
418 ['Kinetic', [[kinetic, kColor]]],
419 ['Potential', [[potential, pColor]]],
420 ['Total', [[kinetic, kColor], [potential, pColor]]],
421 ];
422 rows.forEach(([label, segments], i) => {
423 const y = 10 + i * rowH;
424 ctx.fillStyle = fg;
425 ctx.fillText(label, barX - 12, y + barH / 2);
427 // outline at full scale, then filled segments
428 ctx.strokeStyle = fg;
429 ctx.globalAlpha = 0.25;
430 ctx.lineWidth = 1;
431 ctx.strokeRect(barX + 0.5, y + 0.5, barW, barH);
432 ctx.globalAlpha = 1;
433 let sx = barX;
434 for (const [value, col] of segments) {
435 const sw = Math.min(value / total, 1) * barW;
436 ctx.fillStyle = col;
437 ctx.fillRect(sx, y, sw, barH);
438 sx += sw;
439 }
440 });
441}
443// Phase plot: q horizontal (lined up with the spring diagram), p vertical.
444// The axes are fixed so changing k and m visibly reshapes the orbit.
445const pMax = 3;
447function drawPhase(canvas, params, trail, q, p) {
448 if (!canvas.clientWidth) return;
449 const { ctx, w, h } = prepare(canvas);
450 const { rest, swing, qToX } = layout(w);
451 const mid = h / 2;
452 const pToY = (pv) => mid - (pv / pMax) * (h / 2 - 16);
453 const fg = color('--fg');
454 const accent = color('--accent');
456 // axes
457 ctx.strokeStyle = fg;
458 ctx.fillStyle = fg;
459 ctx.globalAlpha = 0.5;
460 ctx.lineWidth = 1;
461 ctx.beginPath();
462 ctx.moveTo(rest - swing - 20, mid);
463 ctx.lineTo(rest + swing + 20, mid);
464 ctx.moveTo(rest, 8);
465 ctx.lineTo(rest, h - 8);
466 ctx.stroke();
467 ctx.globalAlpha = 1;
468 ctx.font = 'italic 18px Georgia, serif';
469 ctx.textAlign = 'left';
470 ctx.textBaseline = 'middle';
471 ctx.fillText('q', rest + swing + 26, mid);
472 ctx.textBaseline = 'top';
473 ctx.fillText('p', rest + 8, 6);
475 // level curve H = k q0^2 / 2: an ellipse with semi-axes q0 and q0 sqrt(k m)
476 const { k, m, q0 } = params;
477 const rx = Math.abs(q0) * swing;
478 const ry = Math.abs(pToY(Math.abs(q0) * Math.sqrt(k * m)) - mid);
479 ctx.strokeStyle = fg;
480 ctx.globalAlpha = 0.35;
481 ctx.setLineDash([4, 4]);
482 ctx.beginPath();
483 ctx.ellipse(rest, mid, rx, ry, 0, 0, 2 * Math.PI);
484 ctx.stroke();
485 ctx.setLineDash([]);
486 ctx.globalAlpha = 1;
488 // trail, then the current state
489 ctx.strokeStyle = accent;
490 ctx.lineWidth = 2;
491 ctx.beginPath();
492 trail.forEach(([tq, tp], i) => {
493 if (i === 0) ctx.moveTo(qToX(tq), pToY(tp));
494 else ctx.lineTo(qToX(tq), pToY(tp));
495 });
496 ctx.stroke();
497 ctx.fillStyle = accent;
498 ctx.beginPath();
499 ctx.arc(qToX(q), pToY(p), 6, 0, 2 * Math.PI);
500 ctx.fill();
501}
503// Page 1: the spring and its equations of motion
504const springParams = { k: 6.25, m: 1, q0: 0.6 };
505const spring = createSpring({
506 canvas: document.getElementById('spring-canvas'),
507 button: document.getElementById('spring-toggle'),
508 params: springParams,
509});
511// Page 2: the same spring, with energy bars. Slower and without the arrows,
512// so the moving bars are the only thing to watch.
513const energyBars = document.getElementById('energy-bars');
514const energy = createSpring({
515 canvas: document.getElementById('energy-canvas'),
516 button: document.getElementById('energy-toggle'),
517 params: springParams,
518 speed: 0.5,
519 onDraw: (q, p) => drawEnergyBars(energyBars, springParams, q, p),
520});
522// Page 4: phase space, with adjustable q0, k and m
523const phaseParams = { k: 4, m: 1, q0: 0.6 };
524const phaseCanvas = document.getElementById('phase-canvas');
525const phasePlot = document.getElementById('phase-plot');
526const q0Slider = document.getElementById('phase-q0');
527let phaseTrail = [];
528const phase = createSpring({
529 canvas: phaseCanvas,
530 button: document.getElementById('phase-toggle'),
531 params: phaseParams,
532 labels: ['q', 'p', 'k', 'q0'],
533 pScale: 1 / pMax,
534 onDraw: (q, p) => {
535 phaseTrail.push([q, p]);
536 if (phaseTrail.length > 2000) phaseTrail.shift();
537 drawPhase(phasePlot, phaseParams, phaseTrail, q, p);
538 alignSlider();
539 },
540});
542// Stretch the q0 slider so its thumb sits directly under q0 on the diagram.
543function alignSlider() {
544 const { rest, swing } = layout(phaseCanvas.clientWidth);
545 const thumb = 16;
546 q0Slider.style.width = `${2 * swing + thumb}px`;
547 q0Slider.style.marginLeft = `${rest - swing - thumb / 2}px`;
548}
550for (const name of ['q0', 'k', 'm']) {
551 const input = document.getElementById(`phase-${name}`);
552 const output = document.getElementById(`phase-${name}-value`);
553 input.value = phaseParams[name];
554 output.textContent = phaseParams[name];
555 input.addEventListener('input', () => {
556 phaseParams[name] = Number(input.value);
557 output.textContent = input.value;
558 phaseTrail = [];
559 phase.reset();
560 });
561}
563// Page 5: the pendulum
564const pendulum = createPendulum({
565 canvas: document.getElementById('pendulum-canvas'),
566 button: document.getElementById('pendulum-toggle'),
567 params: { m: 1, L: 1, g: 9.8, theta0: 1.0, p0: 0 },
568});
570// Page 6: pendulum phase space. theta runs across [-pi, pi]; p is fixed at
571// +/- pendulumPMax, which fits the separatrix at the default parameters
572// with room for rotations.
573const pendulumPMax = 12;
574const pendulumDefaults = { m: 1, L: 1, g: 9.8 };
575const pendulumParams = { ...pendulumDefaults, theta0: 0.3, p0: 0 };
576const pendulumPresets = {
577 small: { theta0: 0.3, p0: 0 },
578 large: { theta0: 2.5, p0: 0 },
579 top: { theta0: 3.1, p0: 0 },
580 rotation: { theta0: 0, p0: 8 },
581 balanced: { theta0: Math.PI - 1e-6, p0: 0 }, // a tiny nudge, so it falls after a few seconds
582 rest: { theta0: 0, p0: 0 },
583};
584const pendulumPlot = document.getElementById('pendulum-plot');
585let pendulumTrail = [];
586const pendulumPhase = createPendulum({
587 canvas: document.getElementById('pendulum-phase-canvas'),
588 button: document.getElementById('pendulum-phase-toggle'),
589 params: pendulumParams,
590 labels: ['theta', 'p'],
591 centered: true,
592 pScale: 60 / pendulumPMax,
593 onDraw: (theta, p) => {
594 pendulumTrail.push([theta, p]);
595 if (pendulumTrail.length > 3000) pendulumTrail.shift();
596 drawPendulumPhase(pendulumPlot, pendulumParams, pendulumTrail, theta, p);
597 },
598});
600function drawPendulumPhase(canvas, params, trail, theta, p) {
601 if (!canvas.clientWidth) return;
602 const { ctx, w, h } = prepare(canvas);
603 const { m, L, g } = params;
604 const halfW = Math.min(w / 2 - 30, 300);
605 const cx = w / 2;
606 const mid = h / 2;
607 const thetaToX = (t) => cx + (t / Math.PI) * halfW;
608 const pToY = (pv) => mid - (pv / pendulumPMax) * (h / 2 - 16);
609 const fg = color('--fg');
610 const accent = color('--accent');
612 ctx.save();
613 ctx.beginPath();
614 ctx.rect(cx - halfW, 0, 2 * halfW, h);
615 ctx.clip();
617 // background phase portrait: level curves of H, in units of m g L.
618 // Level 1 is the separatrix between swinging and rotating.
619 const levels = [-0.9, -0.6, -0.2, 0.3, 0.7, 1, 1.5, 2.5, 4];
620 const n = 300;
621 for (const c of levels) {
622 ctx.strokeStyle = fg;
623 ctx.globalAlpha = c === 1 ? 0.45 : 0.15;
624 ctx.lineWidth = c === 1 ? 1.5 : 1;
625 for (const sign of [1, -1]) {
626 ctx.beginPath();
627 let drawing = false;
628 for (let i = 0; i <= n; i++) {
629 const t = -Math.PI + (2 * Math.PI * i) / n;
630 // p^2 / (2 m L^2) - m g L cos(t) = c m g L
631 const p2 = 2 * m * L * L * m * g * L * (c + Math.cos(t));
632 if (p2 < 0) { drawing = false; continue; }
633 const x = thetaToX(t);
634 const y = pToY(sign * Math.sqrt(p2));
635 if (drawing) ctx.lineTo(x, y);
636 else ctx.moveTo(x, y);
637 drawing = true;
638 }
639 ctx.stroke();
640 }
641 }
642 ctx.globalAlpha = 1;
644 // trail, broken where theta wraps around
645 ctx.strokeStyle = accent;
646 ctx.lineWidth = 2;
647 ctx.beginPath();
648 trail.forEach(([tt, tp], i) => {
649 const jump = i > 0 && Math.abs(tt - trail[i - 1][0]) > Math.PI;
650 if (i === 0 || jump) ctx.moveTo(thetaToX(tt), pToY(tp));
651 else ctx.lineTo(thetaToX(tt), pToY(tp));
652 });
653 ctx.stroke();
654 ctx.fillStyle = accent;
655 ctx.beginPath();
656 ctx.arc(thetaToX(theta), pToY(p), 6, 0, 2 * Math.PI);
657 ctx.fill();
658 ctx.restore();
660 // axes
661 ctx.strokeStyle = fg;
662 ctx.fillStyle = fg;
663 ctx.globalAlpha = 0.5;
664 ctx.lineWidth = 1;
665 ctx.beginPath();
666 ctx.moveTo(cx - halfW, mid);
667 ctx.lineTo(cx + halfW, mid);
668 ctx.moveTo(cx, 8);
669 ctx.lineTo(cx, h - 8);
670 ctx.stroke();
671 ctx.globalAlpha = 1;
672 ctx.font = 'italic 18px Georgia, serif';
673 ctx.textBaseline = 'middle';
674 ctx.textAlign = 'left';
675 ctx.fillText('θ', cx + halfW + 6, mid);
676 ctx.textBaseline = 'top';
677 ctx.fillText('p', cx + 8, 6);
678 ctx.font = '13px system-ui, sans-serif';
679 ctx.textAlign = 'center';
680 ctx.fillText('−π', cx - halfW, mid + 6);
681 ctx.fillText('π', cx + halfW, mid + 6);
682}
684const pendulumPreset = document.getElementById('pendulum-preset');
685const pendulumInputs = ['theta0', 'p0', 'm', 'L', 'g'].map((name) => ({
686 name,
687 input: document.getElementById(`pendulum-${name}`),
688 output: document.getElementById(`pendulum-${name}-value`),
689}));
691function syncPendulumInputs() {
692 for (const { name, input, output } of pendulumInputs) {
693 input.value = pendulumParams[name];
694 output.textContent = pendulumParams[name].toFixed(2);
695 }
696}
698function resetPendulumPhase() {
699 pendulumTrail = [];
700 pendulumPhase.reset();
701}
703for (const { name, input, output } of pendulumInputs) {
704 input.addEventListener('input', () => {
705 pendulumParams[name] = Number(input.value);
706 output.textContent = pendulumParams[name].toFixed(2);
707 pendulumPreset.value = 'custom';
708 resetPendulumPhase();
709 });
710}
712// A preset restores the default m, L and g along with its initial state.
713pendulumPreset.addEventListener('change', () => {
714 const preset = pendulumPresets[pendulumPreset.value];
715 if (!preset) return;
716 Object.assign(pendulumParams, pendulumDefaults, preset);
717 syncPendulumInputs();
718 resetPendulumPhase();
719});
720syncPendulumInputs();
722const sims = { spring, energy, phase, pendulum, 'pendulum-phase': pendulumPhase };
724const pageIds = [...document.querySelectorAll('.page')].map((el) => el.id);
725const navPrev = document.getElementById('nav-prev');
726const navNext = document.getElementById('nav-next');
728function show(id) {
729 document.querySelectorAll('.page').forEach((el) => {
730 el.classList.toggle('active', el.id === id);
731 });
732 const i = pageIds.indexOf(id);
733 // label each button with a one-word hint of where it goes
734 const hint = (j) => document.getElementById(pageIds[j])?.dataset.hint ?? '';
735 navPrev.disabled = i === 0;
736 navNext.disabled = i === pageIds.length - 1;
737 navPrev.textContent = `← ${hint(i - 1)}`.trim();
738 navNext.textContent = `${hint(i + 1)} →`.trim();
739 document.getElementById('nav-pos').textContent = `${i + 1} / ${pageIds.length}`;
740 for (const [name, sim] of Object.entries(sims)) {
741 if (name === id) sim.draw();
742 else sim.pause();
743 }
744}
746document.querySelectorAll('[data-tex]').forEach((el) => {
747 katex.render(el.dataset.tex, el, { displayMode: el.tagName === 'DIV' });
748});
750document.querySelectorAll('[data-solution]').forEach((toggle) => {
751 toggle.addEventListener('click', () => {
752 const solution = document.getElementById(toggle.dataset.solution);
753 solution.hidden = !solution.hidden;
754 toggle.textContent = solution.hidden ? 'Show solution' : 'Hide solution';
755 });
756});
758// Pages that start centered: revealing splits them into text and diagram
759// panels and labels the diagram.
760const revealLabels = {
761 spring: ['m', 'k', 'q', 'F', 'p'],
762 energy: [], // stays unlabeled, so the bars are the only thing moving
763 pendulum: ['m', 'L', 'theta', 'p', 'g'],
764};
766document.querySelectorAll('[data-reveal]').forEach((button) => {
767 button.addEventListener('click', () => {
768 const id = button.dataset.reveal;
769 const section = document.getElementById(id);
770 button.hidden = true;
771 section.classList.add('split');
772 section.querySelector('.text').hidden = false;
773 sims[id].setLabels(revealLabels[id]);
774 });
775});
777// The current page lives in the URL hash, so reloading stays put.
778function showFromHash() {
779 const id = location.hash.slice(1);
780 show(document.getElementById(id)?.classList.contains('page') ? id : 'landing');
781 window.scrollTo(0, 0);
782}
784window.addEventListener('hashchange', showFromHash);
785showFromHash();
787document.querySelectorAll('[data-goto]').forEach((el) => {
788 el.addEventListener('click', () => {
789 location.hash = el.dataset.goto;
790 });
791});
793function goToIndex(i) {
794 location.hash = pageIds[Math.max(0, Math.min(pageIds.length - 1, i))];
795}
797function currentIndex() {
798 return pageIds.indexOf(document.querySelector('.page.active').id);
799}
801navPrev.addEventListener('click', () => goToIndex(currentIndex() - 1));
802navNext.addEventListener('click', () => goToIndex(currentIndex() + 1));
804document.addEventListener('keydown', (e) => {
805 if (e.altKey || e.ctrlKey || e.metaKey) return;
806 if (e.target.closest('input, select')) return; // arrow keys belong to the control
807 const target = {
808 ArrowLeft: currentIndex() - 1,
809 ArrowRight: currentIndex() + 1,
810 Home: 0,
811 End: pageIds.length - 1,
812 }[e.key];
813 if (target === undefined) return;
814 e.preventDefault();
815 goToIndex(target);
816});