Watch Encyclopedia / website / exp / refraction.js
| 1 | WE.mount('refraction', function (S) { |
| 2 | var C = S.C, ctx = S.ctx, ang = .7; |
| 3 | var mat = S.select('Material', [['1.333', 'Water'], ['1.52', 'Glass'], ['2.417', 'Diamond']], '1.333'), inside = S.toggle('Shine from inside', false); |
| 4 | S.pointer({ down: set, move: function (x, y, d) { if (d) set(x, y); } }); function set(x, y) { var cx = S.W / 2, cy = S.H / 2, a = Math.atan2(Math.abs(x - cx), Math.abs(y - cy)); ang = Math.max(.02, Math.min(1.54, a)); } |
| 5 | S.loop(function () { |
| 6 | S.clear(); var w = S.W, h = S.H, cx = w / 2, cy = h / 2, n = +mat.v, L = Math.min(w, h) * .46, n1 = inside.v ? n : 1, n2 = inside.v ? 1 : n, s2 = n1 / n2 * Math.sin(ang), tir = s2 > 1, a2 = tir ? 0 : Math.asin(s2), dir = inside.v ? 1 : -1; |
| 7 | ctx.fillStyle = 'rgba(111,177,230,.16)'; ctx.fillRect(0, cy, w, h - cy); S.ln(0, cy, w, cy, 'rgba(111,177,230,.7)', 1.5); ctx.setLineDash([4, 5]); S.ln(cx, cy - L, cx, cy + L, 'rgba(255,255,255,.3)', 1); ctx.setLineDash([]); |
| 8 | S.txt('Air', 14, cy - 16, C.mut, 13); S.txt({ '1.333': 'Water', '1.52': 'Glass', '2.417': 'Diamond' }[mat.v], 14, cy + 18, C.blue, 13); |
| 9 | var sx = cx - L * Math.sin(ang), sy = cy + dir * L * Math.cos(ang); ctx.shadowColor = C.yellow; ctx.shadowBlur = 10; S.ln(sx, sy, cx, cy, C.yellow, 3); |
| 10 | var R0 = Math.pow((n1 - n2) / (n1 + n2), 2), refl = tir ? 1 : R0 + (1 - R0) * Math.pow(1 - Math.cos(ang), 5); |
| 11 | ctx.globalAlpha = Math.max(.15, refl); S.ln(cx, cy, cx + L * Math.sin(ang), cy + dir * L * Math.cos(ang), C.yellow, 3); ctx.globalAlpha = 1; |
| 12 | if (!tir) { ctx.globalAlpha = Math.max(.2, 1 - refl); S.ln(cx, cy, cx + L * Math.sin(a2), cy - dir * L * Math.cos(a2), C.yellow, 3); ctx.globalAlpha = 1; } |
| 13 | ctx.shadowBlur = 0; S.dot(sx, sy, 9, C.yellow); S.ring(sx, sy, 15, 'rgba(240,210,100,.5)', 1.5); |
| 14 | var crit = Math.asin(1 / n) * 180 / Math.PI; |
| 15 | S.txt('In: ' + (ang * 180 / Math.PI).toFixed(0) + '°', cx + 12, cy + dir * 40, C.ink, 13); if (!tir) S.txt('Out: ' + (a2 * 180 / Math.PI).toFixed(0) + '°', cx + 12, cy - dir * 40, C.ink, 13); |
| 16 | S.say(tir ? '<b>Total internal reflection.</b> Past ' + crit.toFixed(0) + '° no light can get out, so the surface acts like a perfect mirror. This is how fiber optic cables carry light, and why diamonds sparkle.' : 'Light slows down in ' + (inside.v ? 'the material and speeds up again in air, so it bends away from the dotted line' : 'the material, so it bends toward the dotted line') + '. <b>Drag the light</b> to change its angle.' + (inside.v ? ' Keep going past ' + crit.toFixed(0) + '°.' : '')); |
| 17 | }); |
| 18 | }); |