DKL9 GitList
Repositories
DKL9 home
functle
Code
Commits
Branches
Tags
Search
Tree:
6314a1e
Branches
Tags
master
functle
plot.js
Fetch problem, track plays, mobile input
dkl9
commited
6314a1e
at 2025-209 17:33:57
plot.js
Blame
History
Raw
const width = 400, height = 400; const ctx = document.getElementById("plot").getContext("2d"); const bound = 10; const xs = []; const targetYs = []; const clampLow = 1.5; const clampHigh = 20; const guessYsList = []; const darkTheme = matchMedia('(prefers-color-scheme: dark)').matches; let yMin = -clampHigh, yMax = clampHigh; ctx.textBaseline = "middle"; ctx.textAlign = "center"; ctx.fillStyle = darkTheme ? "white" : "black"; ctx.font = `${height * 0.15}px sans-serif`; ctx.fillText("Loading ...", width / 2, height / 2); window.addEventListener("targetReady", () => { for (let i = 0; i <= width; i++) { const x = bound * (2 * i / width - 1); xs.push(x); const yv = evalPostfix(target, x); targetYs.push(yv); } yMin = Math.min(...targetYs); yMax = Math.max(...targetYs); if (isNaN(yMin) || yMin < -clampHigh) yMin = -clampHigh; else if (yMin > -clampLow) yMin = -clampLow; if (isNaN(yMax) || yMax > clampHigh) yMax = clampHigh; else if (yMax < clampLow) yMax = clampLow; redrawAll(); }); function drawAxes() { ctx.clearRect(0, 0, width, height); ctx.beginPath(); const y0 = mapY(0); ctx.moveTo(0, y0); ctx.lineTo(width, y0); const x0 = mapX(0); ctx.moveTo(x0, 0); ctx.lineTo(x0, height); [1, -1].forEach(val => { const px = mapX(val); ctx.moveTo(px, y0 - 5); ctx.lineTo(px, y0 + 5); }); [1, -1].forEach(val => { const py = mapY(val); ctx.moveTo(x0 - 5, py); ctx.lineTo(x0 + 5, py); }); ctx.lineWidth = 1; ctx.strokeStyle = darkTheme ? "white" : "black"; ctx.stroke(); } function drawCurve(ys, color, width = 4, threshold = 1e3) { ctx.beginPath(); let prevValid = false; for (let i = 0; i < xs.length; i++) { const y = ys[i]; if (isFinite(y)) { const px = mapX(xs[i]), py = mapY(y); if (prevValid && Math.abs(y - ys[i - 1]) < threshold) { ctx.lineTo(px, py); } else { ctx.moveTo(px, py); } prevValid = true; } else { prevValid = false; } } ctx.lineWidth = width; ctx.strokeStyle = color; ctx.stroke(); } function redrawAll() { drawAxes(); drawCurve(targetYs, darkTheme ? "lime" : "green"); guessYsList.forEach((ys, idx) => drawCurve(ys, "red", (idx < guessYsList.length - 1) ? 1 : 4)); } function mapX(x) { return (x + bound) / (2 * bound) * width; } function mapY(y) { return height - (y - yMin) / (yMax - yMin) * height; }