// Mass on a frictionless spring. Positions are in units of the maximum // swing drawn on screen, so q lies in [-1, 1]. function color(name) { return getComputedStyle(document.documentElement).getPropertyValue(name).trim(); } // Slides are laid out at 1920 x 1080 and the whole deck is scaled to fit the // window (see fitDeck below). Diagrams are drawn in units of DRAW_SCALE slide // pixels, so their geometry and fonts read well on a full-size slide. const DRAW_SCALE = 1.5; let deckScale = 1; // Size a canvas's backing store to its on-screen pixels (slide size x deck // scale x device pixel ratio) and return a context and size in drawing units. function prepare(canvas) { const ctx = canvas.getContext('2d'); const k = deckScale * (window.devicePixelRatio || 1); const bw = Math.max(1, Math.round(canvas.clientWidth * k)); const bh = Math.max(1, Math.round(canvas.clientHeight * k)); if (canvas.width !== bw || canvas.height !== bh) { canvas.width = bw; canvas.height = bh; } ctx.setTransform(k * DRAW_SCALE, 0, 0, k * DRAW_SCALE, 0, 0); const w = canvas.clientWidth / DRAW_SCALE; const h = canvas.clientHeight / DRAW_SCALE; ctx.clearRect(0, 0, w, h); return { ctx, w, h }; } // Horizontal layout shared by the spring diagram, the q0 slider and the phase plot, // so that a given q sits at the same x on all of them. function layout(w) { const rest = w * 0.5; const swing = Math.min(w * 0.3, 200); return { rest, swing, qToX: (q) => rest + q * swing }; } // Wall, floor and a spring reaching a block centered at position q. drawBody // draws whatever is attached (it gets the scene geometry), before the // rest-position marker goes on top. Returns the geometry for labels. function drawSpringScene(ctx, w, h, q, drawBody) { const fg = color('--fg'); const { rest, swing, qToX } = layout(w); const wallX = 20; const floorY = h * 0.62; const box = 50; const center = qToX(q); const springY = floorY - box / 2; // wall and floor ctx.strokeStyle = fg; ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(wallX, floorY - box * 1.6); ctx.lineTo(wallX, floorY); ctx.lineTo(w - 10, floorY); ctx.stroke(); // spring (zig-zag) const coils = 12; const amp = 10; const start = wallX; const end = center - box / 2; const lead = 12; ctx.lineWidth = 1.5; ctx.beginPath(); ctx.moveTo(start, springY); ctx.lineTo(start + lead, springY); const len = end - start - 2 * lead; for (let i = 0; i < coils; i++) { const sx = start + lead + ((i + 0.5) / coils) * len; ctx.lineTo(sx, springY + (i % 2 ? amp : -amp)); } ctx.lineTo(end - lead, springY); ctx.lineTo(end, springY); ctx.stroke(); const scene = { rest, swing, qToX, floorY, box, springY, amp, start, end, center }; drawBody(scene); // rest position marker ctx.strokeStyle = fg; ctx.globalAlpha = 0.3; ctx.setLineDash([4, 4]); ctx.beginPath(); ctx.moveTo(rest, floorY - box * 1.4); ctx.lineTo(rest, floorY + 34); ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1; return scene; } // params: { k, m, q0, b }, read live so sliders can change them; the damping // coefficient b is optional (default 0, no damping). // labels: which of 'm', 'k', 'q', 'F', 'p', 'q0' to draw. // pScale: length of the p arrow per unit momentum, as a fraction of the swing; // by default the arrow peaks at the same length as q. function createSpring({ canvas, button, params, labels = [], speed = 1, pScale, onDraw = () => {} }) { let q = params.q0; let p = 0; function step(dt) { // velocity Verlet on dq/dt = p/m, dp/dt = -k q. Damping, dp/dt = -(b/m) p, // is solved exactly and split around it (Strang splitting), so phase-space // area shrinks at exactly the rate exp(-b t / m). const { k, m, b = 0 } = params; const decay = Math.exp((-0.5 * b * dt) / m); p *= decay; const f = -k * q; q += (p / m) * dt + (0.5 * f / m) * dt * dt; p += 0.5 * (f - k * q) * dt; p *= decay; } function draw() { if (!canvas.clientWidth) return; const { ctx, w, h } = prepare(canvas); const fg = color('--fg'); const { rest, swing, qToX, floorY, box, springY, amp, start, end, center } = drawSpringScene(ctx, w, h, q, (sc) => { ctx.fillStyle = color('--accent'); ctx.fillRect(sc.center - sc.box / 2, sc.floorY - sc.box, sc.box, sc.box); }); onDraw(q, p); if (!labels.length) return; ctx.font = 'italic 18px Georgia, serif'; ctx.textAlign = 'center'; if (labels.includes('m')) { ctx.fillStyle = color('--bg'); ctx.textBaseline = 'middle'; ctx.fillText('m', center, floorY - box / 2); } if (labels.includes('k')) { ctx.fillStyle = fg; ctx.textBaseline = 'bottom'; ctx.fillText('k', (start + end) / 2, springY - amp - 4); } if (labels.includes('q0')) { // where the block was let go from const x0 = qToX(params.q0); ctx.strokeStyle = fg; ctx.globalAlpha = 0.5; ctx.setLineDash([2, 3]); ctx.beginPath(); ctx.moveTo(x0, floorY - box - 48); ctx.lineTo(x0, floorY); ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1; ctx.fillStyle = fg; ctx.textBaseline = 'bottom'; // the serif font has no subscript zero, so draw it smaller and lower ctx.fillText('q', x0 - 4, floorY - box - 52); ctx.font = 'italic 12px Georgia, serif'; ctx.fillText('0', x0 + 5, floorY - box - 48); ctx.font = 'italic 18px Georgia, serif'; } // q below the floor; F and p above the block const { k, m } = params; const pLen = (pScale ?? 1 / Math.sqrt(k * m)) * swing; if (labels.includes('q')) arrow(ctx, rest, center, floorY + 22, fg, 'q', 'below'); if (labels.includes('F')) arrow(ctx, center, center - q * swing, floorY - box - 40, color('--force'), 'F', 'above'); if (labels.includes('p')) arrow(ctx, center, center + p * pLen, floorY - box - 14, color('--momentum'), 'p', 'above'); } function setLabels(value) { labels = value; draw(); } const loop = createLoop({ button, step, draw, speed }); // Back to being held at q0, at rest. function reset() { q = params.q0; p = 0; loop.reset(); } return { draw, setLabels, reset, pause: loop.pause }; } // Animation driven by a Start / Stop / Continue button. function createLoop({ button, step, draw, speed = 1 }) { let running = false; let lastTime = null; let rafId = null; function frame(t) { if (!running) return; if (lastTime !== null) { const dt = speed * Math.min((t - lastTime) / 1000, 0.05); const n = 4; for (let i = 0; i < n; i++) step(dt / n); } lastTime = t; draw(); rafId = requestAnimationFrame(frame); } function setRunning(value) { running = value; cancelAnimationFrame(rafId); if (running) { lastTime = null; rafId = requestAnimationFrame(frame); } if (running || button.textContent !== 'Start') { button.textContent = running ? 'Stop' : 'Continue'; } } button.addEventListener('click', () => setRunning(!running)); return { pause: () => running && setRunning(false), reset: () => { setRunning(false); button.textContent = 'Start'; draw(); }, }; } // Pendulum: a bob of mass m on a massless rod of length L, angle theta from // straight down, kept in [-pi, pi]. // params: { m, L, g, theta0, p0 }, read live so sliders can change them. // labels: which of 'm', 'L', 'theta', 'p', 'g' to draw. // centered: put the pivot mid-canvas so the bob can go over the top; the rod // is then drawn to scale, with L = 1.2 (the slider's maximum) filling the canvas. // pScale: length of the p arrow in px per unit momentum; by default the arrow // peaks at 70px when let go from theta0 at rest. function createPendulum({ canvas, button, params, labels = [], centered = false, pScale, onDraw = () => {} }) { let theta = params.theta0; let p = params.p0; function step(dt) { // leapfrog on dtheta/dt = p / (m L^2), dp/dt = -m g L sin(theta) const { m, L, g } = params; p -= 0.5 * dt * m * g * L * Math.sin(theta); theta += dt * p / (m * L * L); p -= 0.5 * dt * m * g * L * Math.sin(theta); if (theta > Math.PI) theta -= 2 * Math.PI; if (theta < -Math.PI) theta += 2 * Math.PI; } function draw() { if (!canvas.clientWidth) return; const { ctx, w, h } = prepare(canvas); const fg = color('--fg'); const accent = color('--accent'); const { m, L, g } = params; const px = w / 2; const py = centered ? h / 2 : 30; const maxRod = centered ? h / 2 - 28 : Math.min(h - 80, w * 0.4); const rod = centered ? maxRod * L / 1.2 : maxRod; const bx = px + rod * Math.sin(theta); const by = py + rod * Math.cos(theta); const r = 18; // ceiling (only when hanging from the top) and pivot ctx.strokeStyle = fg; ctx.lineWidth = 2; if (!centered) { ctx.beginPath(); ctx.moveTo(px - 50, py); ctx.lineTo(px + 50, py); ctx.stroke(); } // vertical reference ctx.globalAlpha = 0.3; ctx.setLineDash([4, 4]); ctx.beginPath(); ctx.moveTo(px, py); ctx.lineTo(px, py + rod + r + 10); ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1; // rod and bob ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(px, py); ctx.lineTo(bx, by); ctx.stroke(); ctx.fillStyle = fg; ctx.beginPath(); ctx.arc(px, py, 4, 0, 2 * Math.PI); ctx.fill(); ctx.fillStyle = accent; ctx.beginPath(); ctx.arc(bx, by, r, 0, 2 * Math.PI); ctx.fill(); onDraw(theta, p); ctx.font = 'italic 18px Georgia, serif'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; if (labels.includes('m')) { ctx.fillStyle = color('--bg'); ctx.fillText('m', bx, by); } if (labels.includes('L')) { // beside the middle of the rod, on the side away from the vertical const side = theta >= 0 ? 1 : -1; ctx.fillStyle = fg; ctx.fillText('L', (px + bx) / 2 + side * 14 * Math.cos(theta), (py + by) / 2 - side * 14 * Math.sin(theta)); } if (labels.includes('theta')) { // arc from the vertical to the rod const arcR = Math.min(44, rod * 0.45); ctx.strokeStyle = fg; ctx.fillStyle = fg; ctx.lineWidth = 1.5; ctx.beginPath(); ctx.arc(px, py, arcR, Math.PI / 2, Math.PI / 2 - theta, theta > 0); ctx.stroke(); const mid = Math.PI / 2 - theta / 2; ctx.fillText('θ', px + (arcR + 14) * Math.cos(mid), py + (arcR + 14) * Math.sin(mid)); } if (labels.includes('p')) { // along the direction of motion, perpendicular to the rod const peak = Math.sqrt(2 * m * m * g * L * L * L * (1 - Math.cos(params.theta0))); const len = p * (pScale ?? (peak ? 70 / peak : 0)); const tx = Math.cos(theta); const ty = -Math.sin(theta); const momentum = color('--momentum'); ctx.strokeStyle = momentum; ctx.fillStyle = momentum; ctx.lineWidth = 1.5; ctx.beginPath(); ctx.moveTo(bx, by); ctx.lineTo(bx + tx * len, by + ty * len); ctx.stroke(); if (Math.abs(len) > 8) { const d = Math.sign(len); const ex = bx + tx * len; const ey = by + ty * len; ctx.beginPath(); ctx.moveTo(ex, ey); ctx.lineTo(ex - d * 8 * tx - 4 * ty, ey - d * 8 * ty + 4 * tx); ctx.lineTo(ex - d * 8 * tx + 4 * ty, ey - d * 8 * ty - 4 * tx); ctx.closePath(); ctx.fill(); ctx.fillText('p', ex + d * 12 * tx, ey + d * 12 * ty); } } if (labels.includes('g')) { // gravity, pointing down, off to the side const gx = Math.min(px + maxRod + 50, w - 20); ctx.strokeStyle = fg; ctx.fillStyle = fg; ctx.lineWidth = 1.5; ctx.beginPath(); ctx.moveTo(gx, py + 40); ctx.lineTo(gx, py + 90); ctx.stroke(); ctx.beginPath(); ctx.moveTo(gx, py + 90); ctx.lineTo(gx - 4, py + 82); ctx.lineTo(gx + 4, py + 82); ctx.closePath(); ctx.fill(); ctx.fillText('g', gx + 14, py + 65); } } const loop = createLoop({ button, step, draw }); function setLabels(value) { labels = value; draw(); } // Back to the initial state, held still. function reset() { theta = params.theta0; p = params.p0; loop.reset(); } return { draw, setLabels, reset, pause: loop.pause }; } function arrow(ctx, from, to, y, col, label, side) { const dir = Math.sign(to - from); ctx.strokeStyle = col; ctx.fillStyle = col; ctx.lineWidth = 1.5; ctx.beginPath(); ctx.moveTo(from, y); ctx.lineTo(to, y); ctx.stroke(); if (Math.abs(to - from) > 8) { ctx.beginPath(); ctx.moveTo(to, y); ctx.lineTo(to - dir * 8, y - 4); ctx.lineTo(to - dir * 8, y + 4); ctx.closePath(); ctx.fill(); } ctx.textBaseline = side === 'above' ? 'bottom' : 'top'; ctx.fillText(label, (from + to) / 2, side === 'above' ? y - 4 : y + 4); } // Horizontal bars for kinetic, potential and total energy, scaled to the total. function drawEnergyBars(canvas, params, q, p) { if (!canvas.clientWidth) return; const { ctx, w } = prepare(canvas); const { k, m, q0 } = params; const kinetic = (p * p) / (2 * m); const potential = 0.5 * k * q * q; const total = 0.5 * k * q0 * q0; const fg = color('--fg'); const kColor = color('--momentum'); const pColor = color('--potential'); const labelW = 90; const barW = Math.min(w - labelW - 10, 400); const left = Math.max(0, (w - labelW - barW) / 2); const barX = left + labelW; const rowH = 30; const barH = 18; ctx.font = `15px ${color('--font-body')}`; ctx.textBaseline = 'middle'; ctx.textAlign = 'right'; const rows = [ ['Kinetic', [[kinetic, kColor]]], ['Potential', [[potential, pColor]]], ['Total', [[kinetic, kColor], [potential, pColor]]], ]; rows.forEach(([label, segments], i) => { const y = 10 + i * rowH; ctx.fillStyle = fg; ctx.fillText(label, barX - 12, y + barH / 2); // outline at full scale, then filled segments ctx.strokeStyle = fg; ctx.globalAlpha = 0.25; ctx.lineWidth = 1; ctx.strokeRect(barX + 0.5, y + 0.5, barW, barH); ctx.globalAlpha = 1; let sx = barX; for (const [value, col] of segments) { const sw = Math.min(value / total, 1) * barW; ctx.fillStyle = col; ctx.fillRect(sx, y, sw, barH); sx += sw; } }); } // Phase plot: q horizontal (lined up with the spring diagram), p vertical. // The axes are fixed so changing k and m visibly reshapes the orbit. const pMax = 3; // Draw the q and p axes; returns the mapping from (q, p) to canvas coordinates. function springAxes(ctx, w, h) { const { rest, swing, qToX } = layout(w); const mid = h / 2; const pToY = (pv) => mid - (pv / pMax) * (h / 2 - 16); const fg = color('--fg'); ctx.strokeStyle = fg; ctx.fillStyle = fg; ctx.globalAlpha = 0.5; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(rest - swing - 20, mid); ctx.lineTo(rest + swing + 20, mid); ctx.moveTo(rest, 8); ctx.lineTo(rest, h - 8); ctx.stroke(); ctx.globalAlpha = 1; ctx.font = 'italic 18px Georgia, serif'; ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; ctx.fillText('q', rest + swing + 26, mid); ctx.textBaseline = 'top'; ctx.fillText('p', rest + 8, 6); return { rest, swing, mid, qToX, pToY }; } function drawPhase(canvas, params, trail, q, p) { if (!canvas.clientWidth) return; const { ctx, w, h } = prepare(canvas); const { rest, swing, mid, qToX, pToY } = springAxes(ctx, w, h); const fg = color('--fg'); const accent = color('--accent'); // level curve H = k q0^2 / 2: an ellipse with semi-axes q0 and q0 sqrt(k m) const { k, m, q0 } = params; const rx = Math.abs(q0) * swing; const ry = Math.abs(pToY(Math.abs(q0) * Math.sqrt(k * m)) - mid); ctx.strokeStyle = fg; ctx.globalAlpha = 0.35; ctx.setLineDash([4, 4]); ctx.beginPath(); ctx.ellipse(rest, mid, rx, ry, 0, 0, 2 * Math.PI); ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1; // trail, then the current state ctx.strokeStyle = accent; ctx.lineWidth = 2; ctx.beginPath(); trail.forEach(([tq, tp], i) => { if (i === 0) ctx.moveTo(qToX(tq), pToY(tp)); else ctx.lineTo(qToX(tq), pToY(tp)); }); ctx.stroke(); ctx.fillStyle = accent; ctx.beginPath(); ctx.arc(qToX(q), pToY(p), 6, 0, 2 * Math.PI); ctx.fill(); } // Page 1: the spring and its equations of motion const springParams = { k: 6.25, m: 1, q0: 0.6 }; const spring = createSpring({ canvas: document.getElementById('spring-canvas'), button: document.getElementById('spring-toggle'), params: springParams, }); // Page 2: the same spring, with energy bars. Slower and without the arrows, // so the moving bars are the only thing to watch. const energyBars = document.getElementById('energy-bars'); const energy = createSpring({ canvas: document.getElementById('energy-canvas'), button: document.getElementById('energy-toggle'), params: springParams, speed: 0.5, onDraw: (q, p) => drawEnergyBars(energyBars, springParams, q, p), }); // The spring in phase space, with a slider for each of the named params. // Elements are found by id: `${id}-canvas`, `${id}-plot`, `${id}-${name}`. // Reset clears the trail as well. function createSpringPhase({ id, params, names }) { const canvas = document.getElementById(`${id}-canvas`); const plot = document.getElementById(`${id}-plot`); const q0Slider = document.getElementById(`${id}-q0`); let trail = []; const sim = createSpring({ canvas, button: document.getElementById(`${id}-toggle`), params, labels: ['q', 'p', 'k', 'q0'], pScale: 1 / pMax, onDraw: (q, p) => { trail.push([q, p]); if (trail.length > 2000) trail.shift(); drawPhase(plot, params, trail, q, p); alignSlider(); }, }); // Stretch the q0 slider so its thumb sits directly under q0 on the diagram. // The thumb is 30 slide pixels wide (style.css). function alignSlider() { const { rest, swing } = layout(canvas.clientWidth / DRAW_SCALE); const thumb = 30; q0Slider.style.width = `${2 * swing * DRAW_SCALE + thumb}px`; q0Slider.style.marginLeft = `${(rest - swing) * DRAW_SCALE - thumb / 2}px`; } function reset() { trail = []; sim.reset(); } for (const name of names) { const input = document.getElementById(`${id}-${name}`); const output = document.getElementById(`${id}-${name}-value`); input.value = params[name]; output.textContent = params[name]; input.addEventListener('input', () => { params[name] = Number(input.value); output.textContent = input.value; reset(); }); } return { ...sim, reset }; } // Page 4: phase space, with adjustable q0, k and m const phase = createSpringPhase({ id: 'phase', params: { k: 4, m: 1, q0: 0.6 }, names: ['q0', 'k', 'm'] }); // Page 5: the pendulum const pendulum = createPendulum({ canvas: document.getElementById('pendulum-canvas'), button: document.getElementById('pendulum-toggle'), params: { m: 1, L: 1, g: 9.8, theta0: 1.0, p0: 0 }, }); // Page 6: pendulum phase space. theta runs across [-pi, pi]; p is fixed at // +/- pendulumPMax. The separatrix peaks at p = 2 m L sqrt(g L), and the m, L // and g slider ranges keep that under 12 even at their maximums. const pendulumPMax = 12; const pendulumDefaults = { m: 1, L: 1, g: 9.8 }; const pendulumParams = { ...pendulumDefaults, theta0: 0.3, p0: 0 }; const pendulumPresets = { small: { theta0: 0.3, p0: 0 }, large: { theta0: 2.5, p0: 0 }, top: { theta0: 3.1, p0: 0 }, rotation: { theta0: 0, p0: 8 }, balanced: { theta0: Math.PI - 1e-6, p0: 0 }, // a tiny nudge, so it falls after a few seconds rest: { theta0: 0, p0: 0 }, }; const pendulumPlot = document.getElementById('pendulum-plot'); let pendulumTrail = []; const pendulumPhase = createPendulum({ canvas: document.getElementById('pendulum-phase-canvas'), button: document.getElementById('pendulum-phase-toggle'), params: pendulumParams, labels: ['theta', 'p'], centered: true, pScale: 60 / pendulumPMax, onDraw: (theta, p) => { pendulumTrail.push([theta, p]); if (pendulumTrail.length > 3000) pendulumTrail.shift(); drawPendulumPhase(pendulumPlot, pendulumParams, pendulumTrail, theta, p); }, }); // Draw the pendulum phase portrait (level curves of H) and the theta and p // axes; returns the mapping from (theta, p) to canvas coordinates. function pendulumAxes(ctx, w, h, params) { const { m, L, g } = params; const halfW = Math.min(w / 2 - 30, 300); const cx = w / 2; const mid = h / 2; const thetaToX = (t) => cx + (t / Math.PI) * halfW; const pToY = (pv) => mid - (pv / pendulumPMax) * (h / 2 - 16); const fg = color('--fg'); ctx.save(); ctx.beginPath(); ctx.rect(cx - halfW, 0, 2 * halfW, h); ctx.clip(); // background phase portrait: level curves of H, in units of m g L. // Level 1 is the separatrix between swinging and rotating. const levels = [-0.9, -0.6, -0.2, 0.3, 0.7, 1, 1.5, 2.5, 4]; const n = 300; for (const c of levels) { ctx.strokeStyle = fg; ctx.globalAlpha = c === 1 ? 0.45 : 0.15; ctx.lineWidth = c === 1 ? 1.5 : 1; for (const sign of [1, -1]) { ctx.beginPath(); let drawing = false; for (let i = 0; i <= n; i++) { const t = -Math.PI + (2 * Math.PI * i) / n; // p^2 / (2 m L^2) - m g L cos(t) = c m g L const p2 = 2 * m * L * L * m * g * L * (c + Math.cos(t)); if (p2 < 0) { drawing = false; continue; } const x = thetaToX(t); const y = pToY(sign * Math.sqrt(p2)); if (drawing) ctx.lineTo(x, y); else ctx.moveTo(x, y); drawing = true; } ctx.stroke(); } } ctx.globalAlpha = 1; ctx.restore(); // axes ctx.strokeStyle = fg; ctx.fillStyle = fg; ctx.globalAlpha = 0.5; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(cx - halfW, mid); ctx.lineTo(cx + halfW, mid); ctx.moveTo(cx, 8); ctx.lineTo(cx, h - 8); ctx.stroke(); ctx.globalAlpha = 1; ctx.font = 'italic 18px Georgia, serif'; ctx.textBaseline = 'middle'; ctx.textAlign = 'left'; ctx.fillText('θ', cx + halfW + 6, mid); ctx.textBaseline = 'top'; ctx.fillText('p', cx + 8, 6); ctx.font = `13px ${color('--font-body')}`; ctx.textAlign = 'center'; ctx.fillText('−π', cx - halfW, mid + 6); ctx.fillText('π', cx + halfW, mid + 6); return { thetaToX, pToY }; } function drawPendulumPhase(canvas, params, trail, theta, p) { if (!canvas.clientWidth) return; const { ctx, w, h } = prepare(canvas); const { thetaToX, pToY } = pendulumAxes(ctx, w, h, params); const accent = color('--accent'); // trail, broken where theta wraps around ctx.strokeStyle = accent; ctx.lineWidth = 2; ctx.beginPath(); trail.forEach(([tt, tp], i) => { const jump = i > 0 && Math.abs(tt - trail[i - 1][0]) > Math.PI; if (i === 0 || jump) ctx.moveTo(thetaToX(tt), pToY(tp)); else ctx.lineTo(thetaToX(tt), pToY(tp)); }); ctx.stroke(); ctx.fillStyle = accent; ctx.beginPath(); ctx.arc(thetaToX(theta), pToY(p), 6, 0, 2 * Math.PI); ctx.fill(); } const pendulumPreset = document.getElementById('pendulum-preset'); const pendulumInputs = ['theta0', 'p0', 'm', 'L', 'g'].map((name) => ({ name, input: document.getElementById(`pendulum-${name}`), output: document.getElementById(`pendulum-${name}-value`), })); function syncPendulumInputs() { for (const { name, input, output } of pendulumInputs) { input.value = pendulumParams[name]; output.textContent = pendulumParams[name].toFixed(2); } } function resetPendulumPhase() { pendulumTrail = []; pendulumPhase.reset(); } for (const { name, input, output } of pendulumInputs) { input.addEventListener('input', () => { pendulumParams[name] = Number(input.value); output.textContent = pendulumParams[name].toFixed(2); pendulumPreset.value = 'custom'; resetPendulumPhase(); }); } // A preset restores the default m, L and g along with its initial state. pendulumPreset.addEventListener('change', () => { const preset = pendulumPresets[pendulumPreset.value]; if (!preset) return; Object.assign(pendulumParams, pendulumDefaults, preset); syncPendulumInputs(); resetPendulumPhase(); }); syncPendulumInputs(); // Liouville's theorem: a disk of starting points evolves under the flow, and // the area enclosed by its boundary stays constant. // force(q) gives dp/dt; m is the mass term in dq/dt = p / m. // center and radii set the disk in (q, p); the single simulation started from // the center is evolved alongside it. drawDiagram(ctx, w, h, points, jitter, // central) and axes(ctx, w, h) draw the physical picture and the phase-plane axes. function createLiouville({ id, force, m, center, radii, drawDiagram, axes }) { const canvas = document.getElementById(`${id}-canvas`); const diagram = document.getElementById(`${id}-diagram`); const areaOut = document.getElementById(`${id}-area`); const [rq, rp] = radii; // a fine boundary, so the area stays accurate as the disk stretches const nb = 2000; let boundary; let interior; let jitter; let central; function makeDisk() { central = [center[0], center[1]]; boundary = []; for (let i = 0; i < nb; i++) { const a = (2 * Math.PI * i) / nb; boundary.push([center[0] + rq * Math.cos(a), center[1] + rp * Math.sin(a)]); } interior = []; while (interior.length < 600) { const u = 2 * Math.random() - 1; const v = 2 * Math.random() - 1; if (u * u + v * v <= 1) interior.push([center[0] + rq * u, center[1] + rp * v]); } // each point gets a fixed random offset on the diagram, so they form a cloud jitter = interior.map(() => Math.random()); } makeDisk(); function step(dt) { // leapfrog on dq/dt = p / m, dp/dt = force(q), for every point for (const pts of [boundary, interior, [central]]) { for (const pt of pts) { pt[1] += 0.5 * dt * force(pt[0]); pt[0] += dt * pt[1] / m; pt[1] += 0.5 * dt * force(pt[0]); } } } // shoelace formula on the boundary polygon function area() { let a = 0; for (let i = 0; i < nb; i++) { const [q1, p1] = boundary[i]; const [q2, p2] = boundary[(i + 1) % nb]; a += q1 * p2 - q2 * p1; } return Math.abs(a) / 2; } function draw() { if (!canvas.clientWidth) return; const d = prepare(diagram); drawDiagram(d.ctx, d.w, d.h, interior, jitter, central); const { ctx, w, h } = prepare(canvas); const { toX, toY } = axes(ctx, w, h); const accent = color('--accent'); ctx.fillStyle = accent; ctx.globalAlpha = 0.15; ctx.beginPath(); boundary.forEach(([q, p], i) => (i ? ctx.lineTo(toX(q), toY(p)) : ctx.moveTo(toX(q), toY(p)))); ctx.closePath(); ctx.fill(); ctx.globalAlpha = 1; ctx.strokeStyle = accent; ctx.lineWidth = 1.5; ctx.stroke(); for (const [q, p] of interior) ctx.fillRect(toX(q) - 1, toY(p) - 1, 2, 2); areaOut.textContent = area().toFixed(4); } const loop = createLoop({ button: document.getElementById(`${id}-toggle`), step, draw, speed: 0.5 }); function reset() { makeDisk(); loop.reset(); } return { draw, reset, pause: loop.pause }; } // Page 7: the spring, with every block drawn as a point and the spring // reaching the block simulated from the disk's center. The disk's radii look // round at the default scale. const liouvilleSpringK = 4; const liouville = createLiouville({ id: 'liouville', force: (q) => -liouvilleSpringK * q, m: 1, center: [0.5, 0], radii: [0.15, 0.6], drawDiagram: (ctx, w, h, points, jitter, [centralQ]) => { drawSpringScene(ctx, w, h, centralQ, ({ qToX, floorY, box }) => { ctx.fillStyle = color('--accent'); points.forEach(([q], i) => ctx.fillRect(qToX(q) - 1, floorY - 4 - jitter[i] * (box - 8), 2, 2)); }); }, axes: (ctx, w, h) => { const { qToX, pToY } = springAxes(ctx, w, h); return { toX: qToX, toY: pToY }; }, }); // Page 8: the pendulum, with every bob drawn as a point and the rod pointing // at the bob simulated from the disk's center. With m = L = 1, p = dtheta/dt. const liouvillePendulumParams = { m: 1, L: 1, g: 9.8 }; const liouvillePendulum = createLiouville({ id: 'liouville-pendulum', force: (theta) => -liouvillePendulumParams.g * Math.sin(theta), m: 1, center: [1.2, 0], radii: [0.35, 3.5], drawDiagram: (ctx, w, h, points, jitter, [centralTheta]) => { const fg = color('--fg'); const px = w / 2; const py = 30; const rod = Math.min(h - 80, w * 0.4); ctx.strokeStyle = fg; ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(px - 50, py); ctx.lineTo(px + 50, py); ctx.stroke(); ctx.globalAlpha = 0.3; ctx.setLineDash([4, 4]); ctx.beginPath(); ctx.moveTo(px, py); ctx.lineTo(px, py + rod + 28); ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1; ctx.beginPath(); ctx.moveTo(px, py); ctx.lineTo(px + (rod - 18) * Math.sin(centralTheta), py + (rod - 18) * Math.cos(centralTheta)); ctx.stroke(); ctx.fillStyle = color('--accent'); points.forEach(([theta], i) => { const r = rod + (jitter[i] - 0.5) * 30; ctx.fillRect(px + r * Math.sin(theta) - 1, py + r * Math.cos(theta) - 1, 2, 2); }); }, axes: (ctx, w, h) => { const { thetaToX, pToY } = pendulumAxes(ctx, w, h, liouvillePendulumParams); return { toX: thetaToX, toY: pToY }; }, }); // Page 9: the spring in phase space again, with damping const damped = createSpringPhase({ id: 'damped', params: { k: 4, m: 1, q0: 0.6, b: 0.3 }, names: ['q0', 'k', 'm', 'b'] }); // Double pendulum: rod angles theta1, theta2 from straight down and their // momenta p1, p2, as the state z = [theta1, theta2, p1, p2]. // params: { m1, m2, L1, L2, g } plus the initial state { theta1, theta2, p1, p2 }. function doubleKinetic({ m1, m2, L1, L2 }, delta, p1, p2) { const D = m1 + m2 * Math.sin(delta) ** 2; return (m2 * L2 * L2 * p1 * p1 + (m1 + m2) * L1 * L1 * p2 * p2 - 2 * m2 * L1 * L2 * p1 * p2 * Math.cos(delta)) / (2 * m2 * L1 * L1 * L2 * L2 * D); } function doublePotential({ m1, m2, L1, L2, g }, t1, t2) { return -(m1 + m2) * g * L1 * Math.cos(t1) - m2 * g * L2 * Math.cos(t2); } function doubleEnergy(params, [t1, t2, p1, p2]) { return doubleKinetic(params, t1 - t2, p1, p2) + doublePotential(params, t1, t2); } // Hamilton's equations, as written in the recipe: the rates of change of // (theta1, theta2, p1, p2), written into out. function doubleRates(params, t1, t2, p1, p2, out) { const { m1, m2, L1, L2, g } = params; const delta = t1 - t2; const s = Math.sin(delta); const c = Math.cos(delta); const D = m1 + m2 * s * s; const T = doubleKinetic(params, delta, p1, p2); const dTdDelta = (p1 * p2 * s / (L1 * L2) - m2 * T * Math.sin(2 * delta)) / D; out[0] = (L2 * p1 - L1 * p2 * c) / (L1 * L1 * L2 * D); out[1] = ((m1 + m2) * L1 * p2 - m2 * L2 * p1 * c) / (m2 * L1 * L2 * L2 * D); out[2] = -(m1 + m2) * g * L1 * Math.sin(t1) - dTdDelta; out[3] = -m2 * g * L2 * Math.sin(t2) + dTdDelta; } // One step of the implicit midpoint rule, z' = z + h f((z + z') / 2), solved by // fixed-point iteration, updating z in place. It is symplectic, and unlike // leapfrog it does not need H to split into a kinetic part in p and a // potential part in q (here the kinetic energy depends on the angles too). // Allocation-free, since the Liouville slide steps hundreds of these per frame. const doubleRate = [0, 0, 0, 0]; function doubleStep(params, z, h) { const [t1, t2, p1, p2] = z; let a1 = t1; let a2 = t2; let b1 = p1; let b2 = p2; for (let it = 0; it < 20; it++) { doubleRates(params, 0.5 * (t1 + a1), 0.5 * (t2 + a2), 0.5 * (p1 + b1), 0.5 * (p2 + b2), doubleRate); const n1 = t1 + h * doubleRate[0]; const n2 = t2 + h * doubleRate[1]; const n3 = p1 + h * doubleRate[2]; const n4 = p2 + h * doubleRate[3]; const change = Math.max(Math.abs(n1 - a1), Math.abs(n2 - a2), Math.abs(n3 - b1), Math.abs(n4 - b2)); a1 = n1; a2 = n2; b1 = n3; b2 = n4; if (change < 1e-12) break; } z[0] = wrapAngle(a1); z[1] = wrapAngle(a2); z[2] = b1; z[3] = b2; } function wrapAngle(t) { return t - 2 * Math.PI * Math.round(t / (2 * Math.PI)); } function doubleInitial({ theta1, theta2, p1, p2 }) { return [theta1, theta2, p1, p2]; } // A label with a subscript, e.g. m with 1, centered at (x, y). The serif font // has no subscript digits, so the digit is drawn smaller and lower. function subText(ctx, base, sub, x, y) { const font = 'italic 18px Georgia, serif'; const small = 'italic 12px Georgia, serif'; ctx.font = font; const bw = ctx.measureText(base).width; ctx.font = small; const sw = ctx.measureText(sub).width; const left = x - (bw + sw + 1) / 2; const align = ctx.textAlign; ctx.textAlign = 'left'; ctx.font = font; ctx.fillText(base, left, y); ctx.font = small; ctx.fillText(sub, left + bw + 1, y + 5); ctx.font = font; ctx.textAlign = align; } // L1 + L2 at the slider maximums. The rods are drawn to scale, with a total // length of maxLength reaching from the pivot (mid-canvas) to the edge, so // either bob can go over the top. const DOUBLE_REACH = 2.5; // labels: which of 'm', 'L', 'theta', 'g' to draw. function drawDoublePendulum(ctx, w, h, params, [t1, t2], labels, maxLength = DOUBLE_REACH) { const fg = color('--fg'); const accent = color('--accent'); const { L1, L2 } = params; const px = w / 2; const py = h / 2; const reach = Math.min(h, w) / 2 - 8; const r = Math.max(9, Math.min(18, reach * 0.1)); const unit = (reach - r) / maxLength; const x1 = px + unit * L1 * Math.sin(t1); const y1 = py + unit * L1 * Math.cos(t1); const x2 = x1 + unit * L2 * Math.sin(t2); const y2 = y1 + unit * L2 * Math.cos(t2); // vertical reference through the pivot ctx.strokeStyle = fg; ctx.lineWidth = 1; ctx.globalAlpha = 0.3; ctx.setLineDash([4, 4]); ctx.beginPath(); ctx.moveTo(px, py); ctx.lineTo(px, py + unit * (L1 + L2) + r); if (labels.includes('theta')) { // and through the upper bob, for theta2 ctx.moveTo(x1, y1); ctx.lineTo(x1, y1 + unit * L2 * 0.7); } ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1; // rods, pivot and bobs ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(px, py); ctx.lineTo(x1, y1); ctx.lineTo(x2, y2); ctx.stroke(); ctx.fillStyle = fg; ctx.beginPath(); ctx.arc(px, py, 4, 0, 2 * Math.PI); ctx.fill(); ctx.fillStyle = accent; for (const [bx, by] of [[x1, y1], [x2, y2]]) { ctx.beginPath(); ctx.arc(bx, by, r, 0, 2 * Math.PI); ctx.fill(); } ctx.font = 'italic 18px Georgia, serif'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; if (labels.includes('m')) { ctx.fillStyle = color('--bg'); subText(ctx, 'm', '1', x1, y1); subText(ctx, 'm', '2', x2, y2); } if (labels.includes('L')) { // beside the middle of each rod, on the side away from the vertical ctx.fillStyle = fg; for (const [sub, ax, ay, bx, by, t] of [['1', px, py, x1, y1, t1], ['2', x1, y1, x2, y2, t2]]) { const side = t >= 0 ? 1 : -1; subText(ctx, 'L', sub, (ax + bx) / 2 + side * 16 * Math.cos(t), (ay + by) / 2 - side * 16 * Math.sin(t)); } } if (labels.includes('theta')) { // arcs from the vertical to each rod ctx.strokeStyle = fg; ctx.fillStyle = fg; ctx.lineWidth = 1.5; for (const [sub, cx, cy, t, len] of [['1', px, py, t1, L1], ['2', x1, y1, t2, L2]]) { const arcR = Math.min(40, unit * len * 0.45); ctx.beginPath(); ctx.arc(cx, cy, arcR, Math.PI / 2, Math.PI / 2 - t, t > 0); ctx.stroke(); const mid = Math.PI / 2 - t / 2; subText(ctx, 'θ', sub, cx + (arcR + 14) * Math.cos(mid), cy + (arcR + 14) * Math.sin(mid)); } } if (labels.includes('g')) { // gravity, pointing down, in the bottom-right corner const gx = w - 24; const gy = h - 40; ctx.strokeStyle = fg; ctx.fillStyle = fg; ctx.lineWidth = 1.5; ctx.beginPath(); ctx.moveTo(gx, gy - 25); ctx.lineTo(gx, gy + 25); ctx.stroke(); ctx.beginPath(); ctx.moveTo(gx, gy + 25); ctx.lineTo(gx - 4, gy + 17); ctx.lineTo(gx + 4, gy + 17); ctx.closePath(); ctx.fill(); ctx.fillText('g', gx - 14, gy); } } // onStep(z) is called after every time step, for recording trails. // maxLength: see drawDoublePendulum; a number, or a function read at each draw. function createDoublePendulum({ canvas, button, params, labels = [], maxLength, onStep = () => {}, onDraw = () => {} }) { let state = doubleInitial(params); function step(dt) { const n = Math.ceil(dt / 0.0025); for (let i = 0; i < n; i++) doubleStep(params, state, dt / n); onStep(state); } function draw() { if (!canvas.clientWidth) return; const { ctx, w, h } = prepare(canvas); drawDoublePendulum(ctx, w, h, params, state, labels, typeof maxLength === 'function' ? maxLength() : maxLength); onDraw(state); } const loop = createLoop({ button, step, draw }); function setLabels(value) { labels = value; draw(); } // Back to the initial state, held still. function reset() { state = doubleInitial(params); loop.reset(); } return { draw, setLabels, reset, pause: loop.pause }; } // Page 10: the double pendulum, let go with both rods horizontal const doubleDefaults = { m1: 1, m2: 1, L1: 1, L2: 1, g: 9.8 }; const doublePendulum = createDoublePendulum({ canvas: document.getElementById('double-canvas'), button: document.getElementById('double-toggle'), params: { ...doubleDefaults, theta1: Math.PI / 2, theta2: Math.PI / 2, p1: 0, p2: 0 }, maxLength: doubleDefaults.L1 + doubleDefaults.L2, // lengths are fixed here, so fill the canvas }); // Page 11: double pendulum phase space, projected onto the (theta1, p1) and // (theta2, p2) planes. The p axes cover the momentum sliders' range, which the // spinning preset needs; page 12 uses the same axes. const DOUBLE_PMAX = 20; // Draw the theta_k and p_k axes; returns the mapping to canvas coordinates. function doubleAxes(ctx, w, h, k) { const halfW = w / 2 - 30; const cx = w / 2; const mid = h / 2; const thetaToX = (t) => cx + (t / Math.PI) * halfW; const pToY = (pv) => mid - (pv / DOUBLE_PMAX) * (h / 2 - 16); const fg = color('--fg'); ctx.strokeStyle = fg; ctx.fillStyle = fg; ctx.globalAlpha = 0.5; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(cx - halfW, mid); ctx.lineTo(cx + halfW, mid); ctx.moveTo(cx, 8); ctx.lineTo(cx, h - 8); ctx.stroke(); ctx.globalAlpha = 1; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; subText(ctx, 'θ', String(k), cx + halfW + 16, mid); subText(ctx, 'p', String(k), cx + 18, 16); ctx.font = `13px ${color('--font-body')}`; ctx.textBaseline = 'top'; ctx.fillText('−π', cx - halfW, mid + 6); ctx.fillText('π', cx + halfW, mid + 6); return { thetaToX, pToY }; } // The trail in the (theta_k, p_k) plane (k = 0 or 1), fading with age and // broken where theta wraps around, then the current state. function drawDoublePlane(canvas, k, trail, state) { if (!canvas.clientWidth) return; const { ctx, w, h } = prepare(canvas); const { thetaToX, pToY } = doubleAxes(ctx, w, h, k + 1); const accent = color('--accent'); ctx.save(); ctx.beginPath(); ctx.rect(0, 0, w, h); ctx.clip(); ctx.strokeStyle = accent; ctx.lineWidth = 1.5; const chunks = 6; for (let c = 0; c < chunks; c++) { const from = Math.floor((trail.length * c) / chunks); const to = Math.min(trail.length, Math.floor((trail.length * (c + 1)) / chunks) + 1); ctx.globalAlpha = 0.15 + (0.75 * (c + 1)) / chunks; ctx.beginPath(); for (let i = from; i < to; i++) { const z = trail[i]; const x = thetaToX(z[k]); const y = pToY(z[k + 2]); if (i === from || Math.abs(z[k] - trail[i - 1][k]) > Math.PI) ctx.moveTo(x, y); else ctx.lineTo(x, y); } ctx.stroke(); } ctx.restore(); ctx.fillStyle = accent; ctx.beginPath(); ctx.arc(thetaToX(state[k]), pToY(state[k + 2]), 6, 0, 2 * Math.PI); ctx.fill(); } const doublePresets = { inphase: { theta1: 0.25, theta2: 0.25 * Math.SQRT2, p1: 0, p2: 0 }, outphase: { theta1: 0.25, theta2: -0.25 * Math.SQRT2, p1: 0, p2: 0 }, small: { theta1: 0.4, theta2: 0, p1: 0, p2: 0 }, large: { theta1: Math.PI / 2, theta2: Math.PI / 2, p1: 0, p2: 0 }, balanced: { theta1: Math.PI - 1e-6, theta2: Math.PI, p1: 0, p2: 0 }, // a tiny nudge, so it falls after a few seconds spinning: { theta1: 0, theta2: 0, p1: 18, p2: 12 }, // both rods turning together at 6 rad/s rest: { theta1: 0, theta2: 0, p1: 0, p2: 0 }, }; const doubleParams = { ...doubleDefaults, ...doublePresets.small }; const doublePlanes = [1, 2].map((k) => document.getElementById(`double-plane${k}`)); const doubleEnergyOut = document.getElementById('double-energy'); let doubleTrail = []; const doublePhaseSim = createDoublePendulum({ canvas: document.getElementById('double-phase-canvas'), button: document.getElementById('double-phase-toggle'), params: doubleParams, // the canvas is short, so fill it: the rods are drawn to scale relative to // each other, but not across changes of L1 + L2 maxLength: () => doubleParams.L1 + doubleParams.L2, onStep: (z) => { doubleTrail.push(z.slice()); if (doubleTrail.length > 36000) doubleTrail = doubleTrail.slice(-24000); }, onDraw: (z) => { doublePlanes.forEach((canvas, k) => drawDoublePlane(canvas, k, doubleTrail, z)); const e = doubleEnergy(doubleParams, z); doubleEnergyOut.textContent = (Math.abs(e) < 0.005 ? 0 : e).toFixed(2); }, }); function resetDoublePhase() { doubleTrail = []; doublePhaseSim.reset(); } const doublePhase = { ...doublePhaseSim, reset: resetDoublePhase }; const doublePreset = document.getElementById('double-preset'); const doubleInputs = ['theta1', 'theta2', 'p1', 'p2', 'm1', 'm2', 'L1', 'L2', 'g'].map((name) => ({ name, input: document.getElementById(`double-${name}`), output: document.getElementById(`double-${name}-value`), })); function syncDoubleInputs() { for (const { name, input, output } of doubleInputs) { input.value = doubleParams[name]; output.textContent = doubleParams[name].toFixed(2); } } for (const { name, input, output } of doubleInputs) { input.addEventListener('input', () => { doubleParams[name] = Number(input.value); output.textContent = doubleParams[name].toFixed(2); doublePreset.value = 'custom'; resetDoublePhase(); }); } // A preset restores the default masses, lengths and g along with its initial state. doublePreset.addEventListener('change', () => { const preset = doublePresets[doublePreset.value]; if (!preset) return; Object.assign(doubleParams, doubleDefaults, preset); syncDoubleInputs(); resetDoublePhase(); }); syncDoubleInputs(); // Page 12: Liouville's theorem for the double pendulum. A small 4D ball of // starting points around a preset state disperses; it is shown projected onto // the (theta1, p1) and (theta2, p2) planes, with every pendulum's bobs drawn // as points. // The pivot, rods for the central simulation (started from the ball's // center), and every pendulum's two bobs as points. function drawDoubleCloud(ctx, w, h, params, points, [t1, t2]) { const fg = color('--fg'); const { L1, L2 } = params; const px = w / 2; const py = h / 2; const unit = (Math.min(h, w) / 2 - 8) / (L1 + L2); const x1 = px + unit * L1 * Math.sin(t1); const y1 = py + unit * L1 * Math.cos(t1); ctx.strokeStyle = fg; ctx.lineWidth = 1; ctx.globalAlpha = 0.3; ctx.setLineDash([4, 4]); ctx.beginPath(); ctx.moveTo(px, py); ctx.lineTo(px, py + unit * (L1 + L2)); ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1; ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(px, py); ctx.lineTo(x1, y1); ctx.lineTo(x1 + unit * L2 * Math.sin(t2), y1 + unit * L2 * Math.cos(t2)); ctx.stroke(); ctx.fillStyle = fg; ctx.beginPath(); ctx.arc(px, py, 4, 0, 2 * Math.PI); ctx.fill(); ctx.fillStyle = color('--accent'); for (const [a1, a2] of points) { const bx = px + unit * L1 * Math.sin(a1); const by = py + unit * L1 * Math.cos(a1); ctx.fillRect(bx - 1, by - 1, 2, 2); ctx.fillRect(bx + unit * L2 * Math.sin(a2) - 1, by + unit * L2 * Math.cos(a2) - 1, 2, 2); } } function createDoubleLiouville() { const id = 'liouville-double'; const diagram = document.getElementById(`${id}-diagram`); const planes = [1, 2].map((k) => document.getElementById(`${id}-plane${k}`)); const preset = document.getElementById(`${id}-preset`); const params = { ...doubleDefaults }; // half-widths of the ball in theta1, theta2, p1, p2; roughly round on screen const radii = [0.2, 0.2, 1.2, 1.2]; let points; let central; function makeCloud() { const center = doubleInitial(doublePresets[preset.value]); central = center.slice(); points = []; while (points.length < 600) { const u = [0, 1, 2, 3].map(() => 2 * Math.random() - 1); if (u.reduce((sum, v) => sum + v * v, 0) > 1) continue; const z = center.map((c, i) => c + radii[i] * u[i]); z[0] = wrapAngle(z[0]); z[1] = wrapAngle(z[1]); points.push(z); } } makeCloud(); function step(dt) { const n = Math.ceil(dt / 0.0025); for (const z of [central, ...points]) { for (let i = 0; i < n; i++) doubleStep(params, z, dt / n); } } function draw() { if (!diagram.clientWidth) return; const d = prepare(diagram); drawDoubleCloud(d.ctx, d.w, d.h, params, points, central); const accent = color('--accent'); planes.forEach((canvas, k) => { const { ctx, w, h } = prepare(canvas); const { thetaToX, pToY } = doubleAxes(ctx, w, h, k + 1); ctx.save(); ctx.beginPath(); ctx.rect(0, 0, w, h); ctx.clip(); ctx.fillStyle = accent; for (const z of points) ctx.fillRect(thetaToX(z[k]) - 1, pToY(z[k + 2]) - 1, 2, 2); ctx.restore(); }); } const loop = createLoop({ button: document.getElementById(`${id}-toggle`), step, draw, speed: 0.5 }); function reset() { makeCloud(); loop.reset(); } preset.addEventListener('change', reset); return { draw, reset, pause: loop.pause }; } const liouvilleDouble = createDoubleLiouville(); const sims = { spring, energy, phase, pendulum, 'pendulum-phase': pendulumPhase, liouville, 'liouville-pendulum': liouvillePendulum, damped, double: doublePendulum, 'double-phase': doublePhase, 'liouville-double': liouvilleDouble, }; // Reset buttons next to Start: back to the initial state, with trails cleared. const resets = { 'pendulum-phase': resetPendulumPhase, }; for (const [name, sim] of Object.entries(sims)) { document.getElementById(`${name}-reset`).addEventListener('click', resets[name] ?? sim.reset); } const pages = [...document.querySelectorAll('.page')]; const pageIds = pages.map((p) => p.id); const navPrev = document.getElementById('nav-prev'); const navNext = document.getElementById('nav-next'); const navPos = document.getElementById('nav-pos'); // Flatiron logo on every slide. pages.forEach((p) => { const img = document.createElement('img'); img.className = 'logo'; img.alt = 'Flatiron Institute'; img.src = 'assets/flatiron-logo.png'; p.appendChild(img); }); // Table of contents: the slide counter in the nav bar opens a list of slide // titles; T toggles it and Escape closes it. const toc = document.getElementById('toc'); const tocList = document.getElementById('toc-list'); pages.forEach((p) => { const li = document.createElement('li'); const b = document.createElement('button'); b.textContent = p.querySelector('h1, h2').textContent; b.addEventListener('click', () => { location.hash = p.id; setTocOpen(false); }); li.appendChild(b); tocList.appendChild(li); }); function setTocOpen(open) { toc.hidden = !open; navPos.setAttribute('aria-expanded', String(open)); if (open) tocList.querySelector('.current')?.scrollIntoView({ block: 'nearest' }); } navPos.addEventListener('click', (e) => { e.stopPropagation(); setTocOpen(toc.hidden); }); document.addEventListener('click', (e) => { if (!toc.hidden && !toc.contains(e.target)) setTocOpen(false); }); function show(id) { pages.forEach((p) => p.classList.toggle('active', p.id === id)); const i = pageIds.indexOf(id); const prev = pages[i - 1]; const next = pages[i + 1]; // label each button with a one-word hint of where it goes navPrev.textContent = prev ? `← ${prev.dataset.hint}` : '←'; navNext.textContent = next ? `${next.dataset.hint} →` : '→'; navPrev.disabled = !prev; navNext.disabled = !next; navPos.textContent = `${i + 1} / ${pages.length} \u2630`; tocList.querySelectorAll('button').forEach((b, j) => b.classList.toggle('current', j === i)); for (const [name, sim] of Object.entries(sims)) { if (name === id) sim.draw(); else sim.pause(); } } // Scale the 1920 x 1080 deck to the largest size that fits, centered, and // redraw the visible diagram at the new resolution. const SLIDE_W = 1920; const SLIDE_H = 1080; const MARGIN = 16; const stage = document.querySelector('main'); const deck = document.getElementById('deck'); function fitDeck() { stage.style.bottom = `${document.querySelector('.pager').offsetHeight}px`; const w = stage.clientWidth; const h = stage.clientHeight; deckScale = Math.min((w - 2 * MARGIN) / SLIDE_W, (h - 2 * MARGIN) / SLIDE_H); deck.style.transform = `scale(${deckScale})`; deck.style.left = `${(w - SLIDE_W * deckScale) / 2}px`; deck.style.top = `${(h - SLIDE_H * deckScale) / 2}px`; const active = document.querySelector('.page.active'); if (active) sims[active.id]?.draw(); } window.addEventListener('resize', fitDeck); // Canvas text uses the bundled fonts, so redraw once they have loaded. document.fonts?.ready.then(fitDeck); document.querySelectorAll('[data-tex]').forEach((el) => { katex.render(el.dataset.tex, el, { displayMode: el.tagName === 'DIV' }); }); document.querySelectorAll('[data-solution]').forEach((toggle) => { toggle.addEventListener('click', () => { const solution = document.getElementById(toggle.dataset.solution); solution.hidden = !solution.hidden; toggle.textContent = solution.hidden ? 'Show solution' : 'Hide solution'; }); }); // Pages that start centered: revealing splits them into text and diagram // panels and labels the diagram. const revealLabels = { spring: ['m', 'k', 'q', 'F', 'p'], energy: [], // stays unlabeled, so the bars are the only thing moving pendulum: ['m', 'L', 'theta', 'p', 'g'], double: ['m', 'L', 'theta', 'g'], }; document.querySelectorAll('[data-reveal]').forEach((button) => { button.addEventListener('click', () => { const id = button.dataset.reveal; const section = document.getElementById(id); button.hidden = true; section.classList.add('split'); section.querySelector('.text').hidden = false; sims[id].setLabels(revealLabels[id]); }); }); // Replay of how recipe.md was written, from app/crafted-link.js (npm run crafted-link). if (window.CRAFTED_LINK) { const link = document.getElementById('crafted-link'); link.href = window.CRAFTED_LINK; link.hidden = false; } // The current page lives in the URL hash, so reloading stays put. function showFromHash() { const id = location.hash.slice(1); show(document.getElementById(id)?.classList.contains('page') ? id : 'landing'); window.scrollTo(0, 0); } window.addEventListener('hashchange', showFromHash); fitDeck(); showFromHash(); document.querySelectorAll('[data-goto]').forEach((el) => { el.addEventListener('click', () => { location.hash = el.dataset.goto; }); }); function goToIndex(i) { location.hash = pageIds[Math.max(0, Math.min(pageIds.length - 1, i))]; } function currentIndex() { return pageIds.indexOf(document.querySelector('.page.active').id); } navPrev.addEventListener('click', () => goToIndex(currentIndex() - 1)); navNext.addEventListener('click', () => goToIndex(currentIndex() + 1)); document.addEventListener('keydown', (e) => { if (e.altKey || e.ctrlKey || e.metaKey) return; if (e.target.closest?.('input, select, textarea')) return; // arrow keys belong to the control if (e.key === 't' || e.key === 'T') { setTocOpen(toc.hidden); return; } if (e.key === 'Escape' && !toc.hidden) { setTocOpen(false); return; } const target = { ArrowLeft: currentIndex() - 1, ArrowRight: currentIndex() + 1, Home: 0, End: pageIds.length - 1, }[e.key]; if (target === undefined) return; e.preventDefault(); goToIndex(target); });