WE.mount('pendulum', function (S) {
var C = S.C, ctx = S.ctx, th = .6, om = 0, grab = false, tr = [], lastCross = null, period = 0, clock = 0;
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');
var G = function () { return { px: S.W * (S.small() ? .5 : .36), py: S.H * .1, sc: S.H * .78 / 3 }; };
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; } });
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; }
S.loop(function (dt) {
var g = +grav.v, L = len.v;
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; } }
tr.push(th); if (tr.length > 300) tr.shift();
S.clear(); var q = G(), bx = q.px + Math.sin(th) * L * q.sc, by = q.py + Math.cos(th) * L * q.sc;
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([]);
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);
var T = S.TAU * Math.sqrt(L / g);
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); }
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);
if (period) S.txt('Measured: ' + period.toFixed(2) + ' s', tx, S.H * .16 + (S.small() ? 44 : 58), C.green, 13, 'left', 600);
S.say('Drag the weight and let go. The time for one swing depends only on the length and the gravity, not on how heavy the weight is. Four times the length gives twice the time.');
});
});