summaryrefslogtreecommitdiff
path: root/static/main.js
diff options
context:
space:
mode:
authorMartin Hafskjold Thoresen <martin@vind.ai>2025-01-11 01:01:10 +0100
committerMartin Hafskjold Thoresen <martin@vind.ai>2025-01-11 01:01:10 +0100
commit42fd8cd3560047c88a2167a4d5c5845dd81eb3ec (patch)
treecdbd3817c28ae5264f8cf394684014f7bd4d509f /static/main.js
parent2f2beb79720ec9fd35b993e7ad907ecf32005cde (diff)
downloadmusicgame-42fd8cd3560047c88a2167a4d5c5845dd81eb3ec.tar.gz
musicgame-42fd8cd3560047c88a2167a4d5c5845dd81eb3ec.zip
Add styling and hot reload
Diffstat (limited to 'static/main.js')
-rw-r--r--static/main.js61
1 files changed, 57 insertions, 4 deletions
diff --git a/static/main.js b/static/main.js
index 144254f..183b117 100644
--- a/static/main.js
+++ b/static/main.js
@@ -6,10 +6,10 @@ function getContext() {
return _context;
}
-function loadSample(url) {
- return fetch(url)
- .then((response) => response.arrayBuffer())
- .then((buffer) => getContext().decodeAudioData(buffer));
+async function loadSample(url) {
+ const res = await fetch(url);
+ const buffer = res.arrayBuffer();
+ return getContext().decodeAudioData(buffer);
}
function playSoundSample(sample, sampleNote, noteToPlay) {
@@ -20,3 +20,56 @@ function playSoundSample(sample, sampleNote, noteToPlay) {
source.connect(ctx.destination);
source.start(0);
}
+
+function sigmoid(x) {
+ return 1 / (1 + Math.exp(-x));
+}
+
+function drawNoteLines(canvas) {
+ const ctx = canvas.getContext("2d");
+
+ let clicks = [];
+
+ function render() {
+ const W = 256;
+ const H = 512;
+ ctx.clearRect(0, 0, W, H);
+
+ const L = 1.0;
+ ctx.lineWidth = L;
+ ctx.strokeStyle = "#ccc";
+
+ for (let note = 0; note <= 12; note++) {
+ ctx.beginPath();
+ const y = (note / 12) * (H - L) + L / 2;
+ ctx.moveTo(0, y);
+ ctx.lineTo(W, y);
+ ctx.stroke();
+ }
+
+ let now = Date.now();
+ const R = 10.0;
+ for (const [x, y, t] of clicks) {
+ ctx.beginPath();
+ ctx.arc(x - R, y - R, 10, 0, 2 * Math.PI);
+ const tt = (now - t) / 1000; // [0, 1]
+ const alpha = sigmoid(5 - 10 * tt);
+ ctx.fillStyle = `rgb(0, 99, 228, ${alpha})`;
+ ctx.fill();
+ }
+
+ clicks = clicks.filter((o) => now < o[2] + 1_000);
+ if (clicks.length > 0) {
+ requestAnimationFrame(render);
+ }
+ }
+ render();
+
+ canvas.addEventListener("mousedown", (e) => {
+ const { layerX, layerY } = e;
+ clicks.push([layerX, layerY, Date.now()]);
+ render();
+ });
+}
+
+window.drawNoteLines = drawNoteLines;