Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
410 lines (375 loc) · 14.4 KB
/
Copy pathscript.js
File metadata and controls
410 lines (375 loc) · 14.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
const canvas = document.getElementById('c');
const ctx = canvas.getContext('2d');
const W = 1400, H = 340;
canvas.width = W; canvas.height = H;
let state = { mode:'point', source: {x:80,y:H/2}, lineObj:{x:80,height:90}, lenses:[], selectedLens:null, rayCount:9, showFocal:true, showAxis:true, showLabels:true };
function defaultLenses() {
state.lenses = [
{id:1, x:260, type:'converging', f:60, label:'L1'},
{id:2, x:480, type:'converging', f:60, label:'L2'},
];
}
defaultLenses();
let nextId = 3;
function addLens() {
const type = document.getElementById('lens-type').value;
const f = parseInt(document.getElementById('focal-input').value);
const existingXs = state.lenses.map(l=>l.x);
let x = W/2;
while(existingXs.some(ex=>Math.abs(ex-x)<30)) x+=40;
x = Math.min(W-80, Math.max(80,x));
state.lenses.push({id:nextId, x, type, f, label:'L'+nextId});
nextId++;
state.lenses.sort((a,b)=>a.x-b.x);
updateUI(); draw();
}
function removeLens(id) {
state.lenses = state.lenses.filter(l=>l.id!==id);
if(state.selectedLens===id) state.selectedLens=null;
updateUI(); draw();
}
function selectLens(id) {
state.selectedLens = state.selectedLens===id ? null : id;
const lens = state.lenses.find(l=>l.id===id);
if(lens && state.selectedLens===id) {
document.getElementById('focal-input').value = lens.f;
document.getElementById('focal-val').textContent = lens.f+'px';
}
updateUI(); draw();
}
function updateUI() {
const chips = document.getElementById('lens-chips');
const typeIcon = {converging:'⊕', diverging:'⊖', flat:'▬'};
const dotClass = {converging:'type-dot-conv', diverging:'type-dot-div', flat:'type-dot-flat'};
chips.innerHTML = state.lenses.map(l=>`
<span class="chip ${state.selectedLens===l.id?'active':''}" onclick="selectLens(${l.id})">
<span class="dot ${dotClass[l.type]}"></span>
${l.label} ${typeIcon[l.type]} f=${l.f}px
<span class="rm" onclick="event.stopPropagation();removeLens(${l.id})">×</span>
</span>`).join('');
document.getElementById('stat-lenses').textContent = state.lenses.length;
const sel = state.lenses.find(l=>l.id===state.selectedLens);
document.getElementById('stat-sel').textContent = sel ? sel.label : '—';
document.getElementById('stat-rays').textContent = state.rayCount;
if(state.mode === 'line') {
document.getElementById('stat-sy-label').textContent = 'Obj height';
document.getElementById('stat-sy').textContent = Math.round(state.lineObj.height)+'px';
} else {
document.getElementById('stat-sy-label').textContent = 'Source Y';
document.getElementById('stat-sy').textContent = Math.round(state.source.y)+'px';
}
}
function refract(ray, lens) {
if(Math.abs(ray.dx)<1e-9) return null;
const t = (lens.x - ray.x0) / ray.dx;
if(t<=0.001) return null;
const iy = ray.y0 + t * ray.dy;
const h = iy - H/2;
const inSlope = ray.dy / ray.dx;
let outSlope = lens.type==='flat' ? inSlope :
lens.type==='converging' ? inSlope - h/lens.f : inSlope + h/lens.f;
const len = Math.sqrt(1+outSlope*outSlope);
return {x0:lens.x, y0:iy, dx:1/len, dy:outSlope/len};
}
function traceRay(sx, sy, angle) {
let ray = {x0:sx, y0:sy, dx:Math.cos(angle), dy:Math.sin(angle)};
const pts = [{x:ray.x0, y:ray.y0}];
for(const lens of [...state.lenses].sort((a,b)=>a.x-b.x).filter(l=>l.x>sx)) {
const nr = refract(ray, lens);
if(!nr) break;
pts.push({x:nr.x0, y:nr.y0});
ray = nr;
}
pts.push({x: ray.x0+ray.dx*800, y: ray.y0+ray.dy*800});
return pts;
}
function draw() {
ctx.clearRect(0,0,W,H);
ctx.fillStyle = '#07080f';
ctx.fillRect(0,0,W,H);
const axis = H/2;
if(state.showAxis) {
ctx.save();
ctx.strokeStyle = 'rgba(140,160,220,0.18)';
ctx.lineWidth = 1;
ctx.setLineDash([5,5]);
ctx.beginPath(); ctx.moveTo(0,axis); ctx.lineTo(W,axis); ctx.stroke();
ctx.setLineDash([]);
ctx.restore();
}
for(const lens of state.lenses) {
const lx = lens.x, lh = 110;
const isSel = lens.id === state.selectedLens;
const baseColor = lens.type==='converging' ? '#4a8fe8' : lens.type==='diverging' ? '#e8844a' : '#4fc07a';
const alpha = isSel ? 0.35 : 0.15;
ctx.save();
if(lens.type==='converging') {
ctx.beginPath();
ctx.ellipse(lx-7, axis, 13, lh/2, 0, -Math.PI/2, Math.PI/2);
ctx.ellipse(lx+7, axis, 13, lh/2, 0, Math.PI/2, -Math.PI/2);
ctx.closePath();
} else if(lens.type==='diverging') {
ctx.beginPath();
ctx.moveTo(lx-4, axis-lh/2);
ctx.bezierCurveTo(lx+12, axis-lh/4, lx+12, axis+lh/4, lx-4, axis+lh/2);
ctx.bezierCurveTo(lx+4, axis+lh/4, lx+4, axis-lh/4, lx-4, axis-lh/2);
ctx.closePath();
} else {
ctx.beginPath();
ctx.rect(lx-5, axis-lh/2, 10, lh);
}
ctx.fillStyle = baseColor.replace(')', `,${alpha})`).replace('rgb','rgba').replace('#','rgba(').replace(/^rgba\(([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2}),/, (m,r,g,b) => `rgba(${parseInt(r,16)},${parseInt(g,16)},${parseInt(b,16)},`);
ctx.fillStyle = isSel ? baseColor+'44' : baseColor+'22';
ctx.strokeStyle = isSel ? baseColor : baseColor+'cc';
ctx.lineWidth = isSel ? 2.5 : 1.5;
ctx.fill(); ctx.stroke();
ctx.restore();
if(isSel) {
ctx.save();
ctx.strokeStyle = baseColor+'44';
ctx.lineWidth = 6;
ctx.beginPath(); ctx.moveTo(lx, axis-lh/2-4); ctx.lineTo(lx, axis+lh/2+4);
ctx.stroke();
ctx.restore();
}
if(state.showFocal && lens.type!=='flat') {
[lx-lens.f, lx+lens.f].forEach(fx => {
if(fx>0 && fx<W) {
ctx.save();
ctx.strokeStyle = baseColor+'88';
ctx.lineWidth = 0.5;
ctx.setLineDash([3,3]);
ctx.beginPath(); ctx.moveTo(fx, axis-8); ctx.lineTo(fx, axis+8); ctx.stroke();
ctx.setLineDash([]);
ctx.beginPath(); ctx.arc(fx, axis, 3.5, 0, Math.PI*2);
ctx.fillStyle = baseColor+'cc'; ctx.fill();
ctx.font = '10px sans-serif'; ctx.textAlign = 'center';
ctx.fillStyle = baseColor+'bb';
ctx.fillText(fx < lx ? 'F' : "F'", fx, axis+18);
ctx.restore();
}
});
}
if(state.showLabels) {
ctx.save();
ctx.font = `${isSel?'500 ':''}12px sans-serif`;
ctx.fillStyle = isSel ? baseColor : 'rgba(180,195,240,0.55)';
ctx.textAlign = 'center';
ctx.fillText(lens.label, lx, axis-lh/2-14);
ctx.restore();
}
}
if(state.mode === 'line') {
drawLineObjectAndRays();
} else {
drawPointSourceAndRays();
}
}
function drawPointSourceAndRays() {
const n = state.rayCount;
const spread = 0.52;
for(let i=0; i<n; i++) {
const angle = n===1 ? 0 : -spread/2 + (spread/(n-1))*i;
const t = n===1 ? 0.5 : i/(n-1);
const hue = 265 - t*230;
const pts = traceRay(state.source.x, state.source.y, angle);
ctx.beginPath();
ctx.moveTo(pts[0].x, pts[0].y);
for(let j=1; j<pts.length; j++) ctx.lineTo(pts[j].x, pts[j].y);
ctx.strokeStyle = `hsla(${hue},85%,65%,0.55)`;
ctx.lineWidth = 1.1;
ctx.stroke();
}
const sx=state.source.x, sy=state.source.y;
ctx.save();
ctx.beginPath(); ctx.arc(sx, sy, 18, 0, Math.PI*2);
ctx.fillStyle = 'rgba(255,228,80,0.08)'; ctx.fill();
ctx.beginPath(); ctx.arc(sx, sy, 10, 0, Math.PI*2);
ctx.fillStyle = 'rgba(255,228,80,0.15)'; ctx.fill();
ctx.beginPath(); ctx.arc(sx, sy, 5.5, 0, Math.PI*2);
ctx.fillStyle = '#ffe04e';
ctx.strokeStyle = 'rgba(255,255,200,0.6)';
ctx.lineWidth = 1.5;
ctx.fill(); ctx.stroke();
ctx.restore();
}
function lineIntersection(p1, p2, p3, p4) {
const d1x = p2.x-p1.x, d1y = p2.y-p1.y;
const d2x = p4.x-p3.x, d2y = p4.y-p3.y;
const denom = d1x*d2y - d1y*d2x;
if(Math.abs(denom) < 1e-6) return null;
const t = ((p3.x-p1.x)*d2y - (p3.y-p1.y)*d2x) / denom;
return { x: p1.x + t*d1x, y: p1.y + t*d1y, real: t > 0 };
}
function rayFinalSegment(sx, sy, angle) {
const pts = traceRay(sx, sy, angle);
return [pts[pts.length-2], pts[pts.length-1]];
}
function drawLineObjectAndRays() {
const axis = H/2;
const obj = state.lineObj;
const tipY = axis - obj.height;
const groups = [
{key:'tip', y: tipY, hue:185}, // tip
{key:'mid', y: axis - obj.height/2, hue:300}, // mid
{key:'base', y: axis, hue:50}, // base (on axis)
];
const raysPer = Math.max(3, Math.round(state.rayCount/3));
const spread = 0.42;
const images = {};
for(const g of groups) {
for(let i=0; i<raysPer; i++) {
const angle = raysPer===1 ? 0 : -spread/2 + (spread/(raysPer-1))*i;
const pts = traceRay(obj.x, g.y, angle);
ctx.beginPath();
ctx.moveTo(pts[0].x, pts[0].y);
for(let j=1; j<pts.length; j++) ctx.lineTo(pts[j].x, pts[j].y);
ctx.strokeStyle = `hsla(${g.hue},85%,65%,0.5)`;
ctx.lineWidth = 1.1;
ctx.stroke();
}
const [s1a,s1b] = rayFinalSegment(obj.x, g.y, -spread/2);
const [s2a,s2b] = rayFinalSegment(obj.x, g.y, spread/2);
images[g.key] = lineIntersection(s1a, s1b, s2a, s2b);
}
ctx.save();
ctx.strokeStyle = '#ffe04e';
ctx.lineWidth = 2;
ctx.beginPath(); ctx.moveTo(obj.x, axis); ctx.lineTo(obj.x, tipY); ctx.stroke();
ctx.beginPath();
ctx.moveTo(obj.x, tipY);
ctx.lineTo(obj.x-6, tipY+10);
ctx.lineTo(obj.x+6, tipY+10);
ctx.closePath();
ctx.fillStyle = '#ffe04e';
ctx.fill();
ctx.beginPath(); ctx.arc(obj.x, axis, 5, 0, Math.PI*2);
ctx.fillStyle = '#ffe04e'; ctx.fill();
ctx.restore();
drawImageObject(images, axis);
}
function drawImageObject(images, axis) {
const tipImg = images.tip, baseImg = images.base;
if(!tipImg || !baseImg) return;
if(!isFinite(tipImg.x) || !isFinite(tipImg.y) || !isFinite(baseImg.y)) return;
if(Math.abs(tipImg.x) > 3*W) return;
const imgX = tipImg.x;
const imgTipY = tipImg.y;
const imgBaseY = baseImg.y;
const real = tipImg.real;
const sign = Math.sign(imgTipY - imgBaseY) || 1;
ctx.save();
ctx.strokeStyle = real ? 'rgba(255,255,255,0.85)' : 'rgba(255,255,255,0.5)';
ctx.fillStyle = ctx.strokeStyle;
ctx.lineWidth = 2;
if(!real) ctx.setLineDash([5,4]);
ctx.beginPath(); ctx.moveTo(imgX, imgBaseY); ctx.lineTo(imgX, imgTipY); ctx.stroke();
ctx.setLineDash([]);
ctx.beginPath();
ctx.moveTo(imgX, imgTipY);
ctx.lineTo(imgX-6, imgTipY - sign*10);
ctx.lineTo(imgX+6, imgTipY - sign*10);
ctx.closePath();
ctx.fill();
for(const pt of [images.tip, images.mid, images.base]) {
if(!pt) continue;
ctx.beginPath(); ctx.arc(pt.x, pt.y, 2.5, 0, Math.PI*2);
ctx.fill();
}
ctx.font = '10px sans-serif';
ctx.textAlign = 'center';
const labelY = Math.min(H-35, Math.max(imgTipY, imgBaseY) + 16);
ctx.fillText(real ? 'Image' : 'Virtual image', imgX, labelY);
ctx.restore();
}
let dragTarget=null, dragOffset={x:0,y:0};
function getPos(e) {
const r=canvas.getBoundingClientRect(), sx=W/r.width, sy=H/r.height;
const cx=e.touches?e.touches[0].clientX:e.clientX;
const cy=e.touches?e.touches[0].clientY:e.clientY;
return {x:(cx-r.left)*sx, y:(cy-r.top)*sy};
}
canvas.addEventListener('mousedown', e => {
const p=getPos(e);
if(state.mode === 'line') {
const obj = state.lineObj;
const tipY = H/2 - obj.height;
if(Math.hypot(p.x-obj.x, p.y-tipY)<14) {
dragTarget='lineObj:tip'; return;
}
if(Math.abs(p.x-obj.x)<14 && p.y<=H/2+10 && p.y>=tipY-10) {
dragTarget='lineObj:body'; dragOffset={x:p.x-obj.x}; return;
}
} else if(Math.hypot(p.x-state.source.x, p.y-state.source.y)<20) {
dragTarget='source'; dragOffset={x:p.x-state.source.x, y:p.y-state.source.y}; return;
}
for(const l of state.lenses) {
if(Math.abs(p.x-l.x)<18 && Math.abs(p.y-H/2)<65) {
dragTarget='lens:'+l.id; dragOffset={x:p.x-l.x,y:0};
state.selectedLens=l.id;
document.getElementById('focal-input').value=l.f;
document.getElementById('focal-val').textContent=l.f+'px';
updateUI(); draw(); return;
}
}
if(e.detail===2) {
const type=document.getElementById('lens-type').value;
const f=parseInt(document.getElementById('focal-input').value);
if(p.x>50 && p.x<W-50) {
state.lenses.push({id:nextId, x:Math.round(p.x), type, f, label:'L'+nextId});
nextId++; state.lenses.sort((a,b)=>a.x-b.x); updateUI(); draw();
}
}
});
canvas.addEventListener('mousemove', e => {
if(!dragTarget) return;
const p=getPos(e);
if(dragTarget==='source') {
state.source.x=Math.max(20, Math.min(W-20, p.x-dragOffset.x));
state.source.y=Math.max(20, Math.min(H-20, p.y-dragOffset.y));
} else if(dragTarget==='lineObj:tip') {
const axis = H/2;
state.lineObj.height = Math.max(20, Math.min(axis-20, axis-p.y));
} else if(dragTarget==='lineObj:body') {
state.lineObj.x = Math.max(20, Math.min(W-20, p.x-dragOffset.x));
} else if(dragTarget.startsWith('lens:')) {
const id=parseInt(dragTarget.split(':')[1]);
const l=state.lenses.find(l=>l.id===id);
if(l) l.x=Math.max(50, Math.min(W-50, p.x-dragOffset.x));
}
updateUI(); draw();
});
canvas.addEventListener('mouseup', ()=>{dragTarget=null;});
canvas.addEventListener('mouseleave', ()=>{dragTarget=null;});
document.getElementById('ray-count').addEventListener('input', function() {
state.rayCount=parseInt(this.value);
document.getElementById('ray-val').textContent=this.value;
updateUI(); draw();
});
document.getElementById('focal-input').addEventListener('input', function() {
const f=parseInt(this.value);
document.getElementById('focal-val').textContent=f+'px';
if(state.selectedLens) {
const l=state.lenses.find(l=>l.id===state.selectedLens);
if(l) { l.f=f; updateUI(); draw(); }
}
});
document.getElementById('show-focal-pts').addEventListener('change', function() { state.showFocal=this.checked; draw(); });
document.getElementById('show-axis').addEventListener('change', function() { state.showAxis=this.checked; draw(); });
document.getElementById('show-labels').addEventListener('change', function() { state.showLabels=this.checked; draw(); });
document.querySelectorAll('#mode-tabs .tab').forEach(btn => {
btn.addEventListener('click', function() {
state.mode = this.dataset.mode;
document.querySelectorAll('#mode-tabs .tab').forEach(b => b.classList.toggle('active', b===this));
document.getElementById('hint-bar').textContent = state.mode === 'line'
? 'Drag object base or tip to resize · double-click canvas to add lens'
: 'Drag source or lenses · double-click canvas to add lens';
dragTarget = null;
updateUI(); draw();
});
});
function resetScene() {
state.source={x:80,y:H/2}; state.lineObj={x:80,height:90}; defaultLenses();
state.selectedLens=null; nextId=3; updateUI(); draw();
}
updateUI(); draw();