Branchwell

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

Raw 2.4 KB on 8b38e375b3e16f98454b93adca8e1fbd4fc534c5
1WE.mount('circuit', function (S) {
2 var C = S.C, ctx = S.ctx, off = 0;
3 var V = S.slider('Battery', 1, 24, 9, .5, function (v) { return v.toFixed(1) + ' volts'; }), R = S.slider('Resistance', 2, 100, 30, 1, function (v) { return v + ' ohms'; });
4 S.loop(function (dt) {
5 var I = V.v / R.v, P = V.v * I; off += dt * I * 90;
6 S.clear(); var w = S.W, h = S.H, x0 = w * .18, x1 = w * .82, y0 = h * .2, y1 = h * .72, per = 2 * (x1 - x0) + 2 * (y1 - y0);
7 ctx.strokeStyle = '#b87333'; ctx.lineWidth = 5; ctx.lineJoin = 'round'; ctx.strokeRect(x0, y0, x1 - x0, y1 - y0);
8 function pt(d) { d = ((d % per) + per) % per; if (d < x1 - x0) return [x0 + d, y0]; d -= x1 - x0; if (d < y1 - y0) return [x1, y0 + d]; d -= y1 - y0; if (d < x1 - x0) return [x1 - d, y1]; d -= x1 - x0; return [x0, y1 - d]; }
9 for (var i = 0; i < 46; i++) { var p = pt(i * per / 46 + off); S.dot(p[0], p[1], 3.2, C.blue); }
10 // battery (left side)
11 var by = (y0 + y1) / 2; S.rr(x0 - 20, by - 38, 40, 76, 6, '#22262e', C.mut); S.rr(x0 - 9, by - 46, 18, 9, 2, C.mut); S.txt('+', x0, by - 20, C.red, 18, 'center', 700); S.txt('−', x0, by + 22, C.blue, 20, 'center', 700);
12 // resistor (bottom)
13 var rx = (x0 + x1) / 2; S.rr(rx - 46, y1 - 13, 92, 26, 6, '#3a2f22', C.acc); for (var k = 0; k < Math.round(R.v / 12) + 1; k++) S.ln(rx - 36 + k * 9, y1 - 9, rx - 36 + k * 9, y1 + 9, C.acc, 2); S.txt('Resistor', rx, y1 + 30, C.mut, 12, 'center');
14 // bulb (top)
15 var glow = Math.min(1, P / 20), g = ctx.createRadialGradient(rx, y0 - 26, 2, rx, y0 - 26, 30 + glow * 80); g.addColorStop(0, 'rgba(255,230,140,' + (.25 + glow * .75) + ')'); g.addColorStop(1, 'rgba(255,230,140,0)'); ctx.fillStyle = g; ctx.fillRect(rx - 120, y0 - 140, 240, 240);
16 S.dot(rx, y0 - 26, 24, 'rgba(255,240,190,' + (.12 + glow * .8) + ')'); S.ring(rx, y0 - 26, 24, C.mut, 1.5); S.rr(rx - 9, y0 - 4, 18, 10, 2, C.mut);
17 var tx = x1 + 14, sm = S.small(); if (sm) { tx = x0 + 30; }
18 S.txt(I.toFixed(2) + ' A', sm ? rx : (x0 + x1) / 2, by - 12, C.ink, sm ? 26 : 38, 'center', 700); S.txt('current', (x0 + x1) / 2, by + 16, C.mut, 13, 'center'); S.txt(P.toFixed(1) + ' watts of power', (x0 + x1) / 2, by + 38, C.yellow, 13.5, 'center', 600);
19 S.say('Current = voltage ÷ resistance: <b>' + V.v.toFixed(1) + ' V ÷ ' + R.v + ' Ω = ' + I.toFixed(2) + ' A</b>. Raise the voltage to push harder. Raise the resistance to hold the flow back. The dots show the flow speeding up and slowing down.');
20 });
21});