Branchwell

Watch Encyclopedia / website · watchencyclopedia.org / exp / fourier.js

1WE.mount('fourier', function (S) {
2 var C = S.C, ctx = S.ctx, t = 0, tr = [];
3 var shape = S.select('Target shape', [['square', 'Square'], ['saw', 'Sawtooth'], ['tri', 'Triangle']], 'square', function () { tr = []; });
4 var n = S.slider('Circles', 1, 40, 3, 1, null, function () { tr = []; });
5 function terms() { var out = [], k; for (var i = 0; i < n.v; i++) { if (shape.v === 'square') { k = 2 * i + 1; out.push([k, 4 / Math.PI / k]); } else if (shape.v === 'saw') { k = i + 1; out.push([k, 2 / Math.PI / k * (k % 2 ? 1 : -1)]); } else { k = 2 * i + 1; out.push([k, 8 / Math.PI / Math.PI / k / k * (i % 2 ? -1 : 1)]); } } return out; }
6 function target(x) { var p = ((x % S.TAU) + S.TAU) % S.TAU; return shape.v === 'square' ? (p < Math.PI ? 1 : -1) : shape.v === 'saw' ? (p < Math.PI ? p / Math.PI : p / Math.PI - 2) : (p < Math.PI / 2 ? p / (Math.PI / 2) : p < 1.5 * Math.PI ? 2 - p / (Math.PI / 2) : p / (Math.PI / 2) - 4); }
7 S.loop(function (dt) {
8 t += dt * 1.1; var w = S.W, h = S.H, sm = S.small(), A = sm ? Math.min(w * .13, h * .2) : Math.min(w * .1, h * .24), cx = sm ? w * .2 : w * .2, cy = h * .5, x = cx, y = cy, T = terms();
9 S.clear();
10 T.forEach(function (q) { var r = Math.abs(q[1]) * A, ph = q[0] * t + (q[1] < 0 ? Math.PI : 0), nx = x + r * Math.cos(ph), ny = y - r * Math.sin(ph); S.ring(x, y, r, 'rgba(255,255,255,.14)', 1); S.ln(x, y, nx, ny, C.ink, 1.5); x = nx; y = ny; });
11 S.dot(x, y, 4, C.acc); tr.unshift([t, y]); var gx = sm ? w * .42 : w * .42, gw = w - gx - 14, step = 1.6; if (tr.length > gw / step) tr.length = Math.floor(gw / step);
12 S.ln(x, y, gx, y, 'rgba(213,163,90,.5)', 1); S.ln(gx, cy - A * 1.4, gx, cy + A * 1.4, C.grid, 1); S.ln(gx, cy, gx + gw, cy, C.grid, 1);
13 ctx.beginPath(); tr.forEach(function (v, i) { ctx.lineTo(gx + i * step, cy - target(v[0]) * A); }); ctx.strokeStyle = 'rgba(111,177,230,.4)'; ctx.lineWidth = 1.5; ctx.stroke();
14 ctx.beginPath(); tr.forEach(function (v, i) { ctx.lineTo(gx + i * step, v[1]); }); ctx.strokeStyle = C.acc; ctx.lineWidth = 2.5; ctx.stroke(); S.dot(gx, y, 4, C.acc);
15 S.txt(n.v + (n.v === 1 ? ' circle' : ' circles'), 14, 18, C.ink, 15, 'left', 700); S.txt('Target', gx + gw, cy - A * 1.4 - 6, 'rgba(111,177,230,.8)', 11.5, 'right'); S.txt('Sum of the circles', gx + 8, cy - A * 1.4 - 6, C.acc, 11.5);
16 S.say('Each circle spins at a steady speed and rides on the end of the one before it. With one circle you get a smooth wave. Add more, smaller and faster, and the gold line closes in on the <b>blue target shape</b>. Any repeating shape can be built this way.');
17 });
18});