Branchwell

Watch Encyclopedia / website / exp / waves.js

1WE.mount('waves', function (S) {
2 var C = S.C, ctx = S.ctx, off = document.createElement('canvas'), octx = off.getContext('2d'), img, src = [[.38, .5], [.62, .5]], grab = -1, GW = 180, GH = 100;
3 var wl = S.slider('Wavelength', 4, 30, 12, 1, function (v) { return v + ' units'; }), two = S.toggle('Second source', true);
4 function fit() { GH = Math.round(GW * S.H / S.W); off.width = GW; off.height = GH; img = octx.createImageData(GW, GH); } S.onresize = fit; fit();
5 S.pointer({ down: function (x, y) { grab = -1; src.forEach(function (s, i) { if ((i === 0 || two.v) && Math.hypot(s[0] * S.W - x, s[1] * S.H - y) < 34) grab = i; }); }, move: function (x, y, d) { if (d && grab >= 0) { src[grab][0] = Math.max(.03, Math.min(.97, x / S.W)); src[grab][1] = Math.max(.05, Math.min(.95, y / S.H)); } }, up: function () { grab = -1; } });
6 S.loop(function (dt, t) {
7 var k = S.TAU / wl.v, d = img.data, n = two.v ? 2 : 1, i = 0, sx = [src[0][0] * GW, src[1][0] * GW], sy = [src[0][1] * GH, src[1][1] * GH], ph = t * 7;
8 for (var y = 0; y < GH; y++) for (var x = 0; x < GW; x++) { var v = 0; for (var s = 0; s < n; s++) { var r = Math.hypot(x - sx[s], y - sy[s]); v += Math.sin(k * r - ph) / (1 + r * .012); } v /= n; var p = v > 0 ? v : 0, q = v < 0 ? -v : 0; d[i++] = 13 + p * 215 + q * 10; d[i++] = 15 + p * 165 + q * 90; d[i++] = 19 + p * 90 + q * 210; d[i++] = 255; }
9 octx.putImageData(img, 0, 0); ctx.imageSmoothingEnabled = true; ctx.drawImage(off, 0, 0, S.W, S.H);
10 src.forEach(function (s, j) { if (j === 0 || two.v) { S.dot(s[0] * S.W, s[1] * S.H, 7, '#fff'); S.ring(s[0] * S.W, s[1] * S.H, 13, 'rgba(255,255,255,.7)', 1.5); } });
11 S.say(two.v ? 'Two sets of ripples cross. Where crest meets crest they add up into bright bands. Where crest meets trough they cancel into calm lines. <b>Drag the white dots</b> to move the sources.' : 'One source sends out even rings. Switch on the second source to see the pattern they make together.');
12 });
13});