summaryrefslogtreecommitdiff
path: root/static/main.js
blob: 6b092fa385fc610ce70cc7390b3a9c80b48e7286 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
let _context;
function getContext() {
  if (!_context) {
    _context = new AudioContext();
  }
  return _context;
}

async function loadSample(url) {
  const res = await fetch(url);
  const buffer = await res.arrayBuffer();
  return getContext().decodeAudioData(buffer);
}

function playSoundSample(sample, sampleNote, noteToPlay) {
  const ctx = getContext();
  const source = ctx.createBufferSource();
  source.buffer = sample;
  source.playbackRate.value = 2 ** ((noteToPlay - sampleNote) / 12);
  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;