canvas.html34 lines · 1.4 KB · raw
1<body style="margin: 0">
2  <input
3    type="text"
4    id="text"
5    value="seq('tomato', 'indigo', ['white', 'steelblue']).fast(4)"
6    style="width: 100%; font-size: 2em; background: black; color: white; outline: none; position: absolute; top: 0"
7    spellcheck="false"
8  />
9  <canvas id="canvas"></canvas>
10  <script type="module">
11    const strudel = await import('https://cdn.skypack.dev/@strudel/core@0.6.8');
12    // this adds all strudel functions to the global scope, to be used by eval
13    Object.assign(window, strudel);
14    // setup elements
15    const input = document.getElementById('text');
16    const canvas = document.getElementById('canvas');
17    canvas.width = window.innerWidth;
18    canvas.height = window.innerHeight;
19    const ctx = canvas.getContext('2d');
20    input.focus(); // autofocus
21    input.setSelectionRange(input.value.length, input.value.length); // move cursor to end
22    paint(input.value); // initial paint
23    input.addEventListener('input', (e) => paint(e.target.value)); // repaint on input
24
25    function paint(code) {
26      const pattern = eval(code); // run code
27      const events = pattern.firstCycle(); // query first cycle
28      events.forEach((event) => {
29        ctx.fillStyle = event.value;
30        ctx.fillRect(event.whole.begin * canvas.width, 0, event.duration.valueOf() * canvas.width, canvas.height);
31      });
32    }
33  </script>
34</body>