Branchwell

Watch Encyclopedia / website / exp / pendulum.js

1WE.mount('pendulum', function (S) {
2 var C = S.C, ctx = S.ctx, th = .6, om = 0, grab = false, tr = [], lastCross = null, period = 0, clock = 0;
3 var len = S.slider('Length', .2, 3, 1, .05, function (v) { return v.toFixed(2) + ' m'; }), grav = S.select('Gravity', [['1.62', 'Moon'], ['3.71', 'Mars'], ['9.81', 'Earth'], ['24.79', 'Jupiter']], '9.81');
4 var G = function () { return { px: S.W * (S.small() ? .5 : .36), py: S.H * .1, sc: S.H * .78 / 3 }; };
5 S.pointer({ down: function (x, y) { grab = true; set(x, y); }, move: function (x, y, d) { if (d && grab) set(x, y); }, up: function () { grab = false; om = 0; lastCross = null; period = 0; } });
6 function set(x, y) { var g = G(); th = Math.max(-1.5, Math.min(1.5, Math.atan2(x - g.px, Math.max(5, y - g.py)))); om = 0; }
7 S.loop(function (dt) {
8 var g = +grav.v, L = len.v;
9 if (!grab) for (var i = 0; i < 8; i++) { var h = dt / 8, prev = th; om += -g / L * Math.sin(th) * h; th += om * h; clock += h; if (prev < 0 && th >= 0) { if (lastCross !== null) period = clock - lastCross; lastCross = clock; } }
10 tr.push(th); if (tr.length > 300) tr.shift();
11 S.clear(); var q = G(), bx = q.px + Math.sin(th) * L * q.sc, by = q.py + Math.cos(th) * L * q.sc;
12 S.ln(q.px - 50, q.py, q.px + 50, q.py, C.mut, 3); ctx.setLineDash([4, 5]); S.ln(q.px, q.py, q.px, q.py + L * q.sc + 20, 'rgba(255,255,255,.2)', 1); ctx.setLineDash([]);
13 S.ln(q.px, q.py, bx, by, C.ink, 2); S.dot(bx, by, 16, C.acc); S.ring(bx, by, 21, grab ? C.ink : 'rgba(213,163,90,.4)', 1.5);
14 var T = S.TAU * Math.sqrt(L / g);
15 if (!S.small()) { var gx = S.W * .62, gw = S.W * .33, gy = S.H * .62; S.ln(gx, gy, gx + gw, gy, C.grid, 1); ctx.beginPath(); tr.forEach(function (v, i) { ctx.lineTo(gx + gw * i / 300, gy - v * 60); }); ctx.strokeStyle = C.blue; ctx.lineWidth = 2; ctx.stroke(); S.txt('Swing over time', gx, gy - 110, C.mut, 12.5); }
16 var tx = S.small() ? 14 : S.W * .62; S.txt(T.toFixed(2) + ' s', tx, S.H * .16, C.ink, S.small() ? 26 : 40, 'left', 700); S.txt('for one full swing', tx, S.H * .16 + (S.small() ? 24 : 34), C.mut, 13);
17 if (period) S.txt('Measured: ' + period.toFixed(2) + ' s', tx, S.H * .16 + (S.small() ? 44 : 58), C.green, 13, 'left', 600);
18 S.say('Drag the weight and let go. The time for one swing depends only on the <b>length</b> and the <b>gravity</b>, not on how heavy the weight is. Four times the length gives twice the time.');
19 });
20});