// Drawing helpers shared by the diagrams, and the Start / Stop animation loop. export 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 (deck.js sets the scale). Diagrams are drawn in units of DRAW_SCALE // slide pixels, so their geometry and fonts read well on a full-size slide. export const DRAW_SCALE = 1.5; let deckScale = 1; export function setDeckScale(scale) { deckScale = scale; } // 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. export 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 }; } // A horizontal arrow at height y from x = from to x = to, labeled above or below. export 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); } // Animation driven by a Start / Stop / Continue button. step(dt) advances the // simulation; speed is a number, or a function read every frame so it can // change while running. export 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 = (typeof speed === 'function' ? speed() : 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 { isRunning: () => running, start: () => running || setRunning(true), pause: () => running && setRunning(false), reset: () => { setRunning(false); button.textContent = 'Start'; draw(); }, }; }