Branchwell

Watch Encyclopedia / website / exp / strings.js

1WE.mount('strings', function (S) {
2 var C = S.C, ctx = S.ctx, on = [1, 0, 0, 0, 0, 0], tg = [], osc = [], actx = null, BASE = 110;
3 for (var i = 0; i < 6; i++) (function (i) { tg.push(S.toggle(i === 0 ? 'Base note' : 'Harmonic ' + (i + 1), i === 0, function (v) { on[i] = v ? 1 : 0; sync(); })); })(i);
4 var snd = S.toggle('Sound', false, function () { sync(); });
5 function sync() { try { if (!snd.v) { osc.forEach(function (o) { if (o) o.g.gain.value = 0; }); return; } actx = actx || new (window.AudioContext || window.webkitAudioContext)(); if (actx.state === 'suspended') actx.resume(); for (var i = 0; i < 6; i++) { if (!osc[i]) { var o = actx.createOscillator(), g = actx.createGain(); o.frequency.value = BASE * (i + 1); g.gain.value = 0; o.connect(g); g.connect(actx.destination); o.start(); osc[i] = { o: o, g: g }; } osc[i].g.gain.setTargetAtTime(on[i] ? .1 / (i + 1) : 0, actx.currentTime, .03); } } catch (e) { } }
6 S.loop(function (dt, t) {
7 S.clear(); var w = S.W, h = S.H, x0 = w * .08, x1 = w * .92, cy = h * .32, amp = h * .16;
8 S.dot(x0, cy, 6, C.mut); S.dot(x1, cy, 6, C.mut);
9 ctx.beginPath(); for (var x = 0; x <= 200; x++) { var u = x / 200, y = 0; for (var n = 0; n < 6; n++) if (on[n]) y += Math.sin((n + 1) * Math.PI * u) * Math.cos((n + 1) * t * 3.2) / (n + 1); ctx.lineTo(x0 + u * (x1 - x0), cy + y * amp); } ctx.strokeStyle = C.acc; ctx.lineWidth = 3; ctx.stroke();
10 S.txt('The string', x0, cy - amp - 22, C.mut, 12.5);
11 var rows = on.reduce(function (a, b) { return a + b; }, 0), k = 0, ry = h * .58, rh = (h * .38) / 6;
12 for (var m = 0; m < 6; m++) { var yy = ry + m * rh + rh / 2; ctx.beginPath(); for (var q = 0; q <= 120; q++) { var uu = q / 120; ctx.lineTo(x0 + uu * (x1 - x0), yy + Math.sin((m + 1) * Math.PI * uu) * Math.cos((m + 1) * t * 3.2) * rh * .36 * (on[m] ? 1 : .0)); } ctx.strokeStyle = on[m] ? [C.acc, C.blue, C.green, C.pink, C.violet, C.teal][m] : C.grid; ctx.lineWidth = on[m] ? 2 : 1; ctx.stroke(); S.txt(BASE * (m + 1) + ' Hz', x0 - 6, yy, on[m] ? C.ink : C.dim, 11, 'right'); if (on[m]) for (var nd = 1; nd <= m; nd++) S.dot(x0 + nd / (m + 1) * (x1 - x0), yy, 3, C.ink); }
13 S.say(rows === 0 ? 'Switch a note on.' : 'A string can only wobble in whole numbers of loops: one, two, three and so on. Each pattern is a pure note, and the still points are called nodes. A real instrument plays <b>several at once</b>, and that mix is what gives it its own voice. ' + (snd.v ? '' : 'Turn on Sound to hear it.'));
14 });
15});