-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvectors.html
1196 lines (1148 loc) · 32.1 KB
/
vectors.html
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Drawing App – Enhanced Merge Points + Chain Straightening</title>
<style>
body, html {
margin: 0;
padding: 0;
height: 100%;
overflow: hidden;
user-select: none;
font-family: Arial, sans-serif;
}
#canvas {
display: block;
background-color: #fff;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
// ======================================================
// Global Variables
// ======================================================
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.addEventListener("contextmenu", e => e.preventDefault());
const pxPerCm = 35;
const snapRadius = 15;
let endpoints = []; // Each ep: { x, y, lines: [], selected: bool, parentCircle?: ... }
let lines = [];
let circles = [];
let isPanning = false;
let panOffset = { x:0, y:0 };
let panStart = { x:0, y:0 };
let oldPan = { x:0, y:0 };
let isDrawingLine = false;
let startEndpoint = null;
let currentPosLine = { x:0, y:0 };
let isDrawingCircle = false;
let circleCenter = null;
let currentPosCircle = { x:0, y:0 };
let vKeyHeld = false; // “V” => circle creation
// Endpoint dragging
let isDraggingEndpoint = false;
let draggedEndpoints = [];
let dragStartPos = { x:0, y:0 };
let endpointsOriginalPos = [];
// Selection rectangle
let isSelecting = false;
let selectionStart = null;
let selectionCurrent = null;
// Undo/Redo
const undoStack = [];
const redoStack = [];
// Toggles
let labelsVisible = true; // toggled by “H”
let showAngles = true; // toggled by “I”
let showLineLengths = false; // toggled by “U”
let shiftIsHeld = false;
let hoverEndpoint = null;
// ======================================================
// Utility Functions
// ======================================================
function getMousePos(e){
const rect = canvas.getBoundingClientRect();
return {
x: e.clientX - rect.left + panOffset.x,
y: e.clientY - rect.top + panOffset.y
};
}
function dist(a,b){
return Math.hypot(a.x - b.x, a.y - b.y);
}
function pointInRect(p, start, current){
let xMin = Math.min(start.x, current.x);
let xMax = Math.max(start.x, current.x);
let yMin = Math.min(start.y, current.y);
let yMax = Math.max(start.y, current.y);
return (p.x >= xMin && p.x <= xMax && p.y >= yMin && p.y <= yMax);
}
function findEndpoint(x,y){
for(let ep of endpoints){
if(dist(ep,{ x,y }) <= snapRadius) return ep;
}
return null;
}
function cleanupEndpoints(){
for(let i=endpoints.length-1; i>=0; i--){
if(endpoints[i].lines.length===0){
endpoints.splice(i,1);
}
}
}
function getSnappedEndpoint(x,y){
// If extremely close => reuse
for(let ep of endpoints){
if(dist(ep,{x,y}) < 1e-6) return ep;
}
let found = findEndpoint(x,y);
if(found) return found;
let ep = { x, y, lines:[], selected:false };
endpoints.push(ep);
return ep;
}
function lineExists(ep1, ep2){
return lines.some(ln=>
(ln.start=== ep1 && ln.end=== ep2) ||
(ln.start=== ep2 && ln.end=== ep1)
);
}
// SHIFT line constraints => multiples of 45°, plus parallel/perp
function applyConstraints(origin, curr, shiftHeld){
if(!shiftHeld) return { x: curr.x, y: curr.y };
let { x: ox, y: oy } = origin;
let { x: cx, y: cy } = curr;
let inputAngle = Math.atan2(cy- oy, cx- ox);
if(inputAngle<0) inputAngle += 2*Math.PI;
let cand45 = Math.round(inputAngle/(Math.PI/4))*(Math.PI/4);
let candidates= [ cand45 ];
origin.lines.forEach(ln=>{
let other = (ln.start=== origin)? ln.end : ln.start;
let a = Math.atan2(other.y- oy, other.x- ox);
if(a<0) a+= 2*Math.PI;
candidates.push(a);
candidates.push((a + Math.PI)%(2*Math.PI));
candidates.push((a + Math.PI/2)%(2*Math.PI));
candidates.push((a + 3*Math.PI/2)%(2*Math.PI));
});
let best= candidates[0];
let minDiff= Math.abs(inputAngle- best);
if(minDiff> Math.PI) minDiff= 2*Math.PI- minDiff;
candidates.forEach(c=>{
let diff= Math.abs(inputAngle- c);
if(diff> Math.PI) diff= 2*Math.PI- diff;
if(diff< minDiff){
minDiff= diff;
best= c;
}
});
let distance= Math.hypot(cx- ox, cy- oy);
cx= ox+ distance* Math.cos(best);
cy= oy+ distance* Math.sin(best);
return { x: cx, y: cy };
}
function snapDraggedEndpoint(pos, excludeList){
for(let ep of endpoints){
if(excludeList.includes(ep)) continue;
if(dist(ep,pos)<= snapRadius){
return { x: ep.x, y: ep.y };
}
}
return pos;
}
// BFS to gather the “chain” from hovered ep
function findChainEndpoints(ep){
let chain= new Set();
let queue= [ ep ];
while(queue.length>0){
let current= queue.shift();
if(chain.has(current)) continue;
chain.add(current);
// Continue BFS if current=== ep or lines.length===2
if(current=== ep || current.lines.length===2){
current.lines.forEach(ln=>{
let nb= (ln.start=== current)? ln.end: ln.start;
if(!chain.has(nb)) queue.push(nb);
});
}
}
return Array.from(chain);
}
// ======================================================
// Classes
// ======================================================
class Line {
constructor(startEp, endEp){
this.start= startEp;
this.end= endEp;
this.length= dist(startEp, endEp)/ pxPerCm;
startEp.lines.push(this);
endEp.lines.push(this);
}
draw(){
ctx.strokeStyle= "#333";
ctx.lineWidth=2;
ctx.beginPath();
ctx.moveTo(this.start.x,this.start.y);
ctx.lineTo(this.end.x,this.end.y);
ctx.stroke();
}
}
class Circle {
constructor(centerEp, radius){
this.center= centerEp;
this.radius= radius;
this.samplePoints= this.calcPoints();
this.samplePoints.forEach(pt=>{
pt.parentCircle= this;
endpoints.push(pt);
});
circles.push(this);
}
calcPoints(){
let n= Math.ceil(this.radius/20);
n= Math.max(8, Math.min(n,64));
let arr= [];
for(let i=0;i<n;i++){
let angle= (2*Math.PI/n)* i;
let x= this.center.x+ this.radius*Math.cos(angle);
let y= this.center.y+ this.radius*Math.sin(angle);
arr.push({ x,y, lines:[], selected:false, parentCircle:this });
}
return arr;
}
draw(){
ctx.strokeStyle= "#FF5733";
ctx.lineWidth=2;
ctx.beginPath();
ctx.arc(this.center.x,this.center.y, this.radius,0,2*Math.PI);
ctx.stroke();
ctx.fillStyle= "#FF0000";
this.samplePoints.forEach(pt=>{
ctx.beginPath();
ctx.arc(pt.x, pt.y,6,0,2*Math.PI);
ctx.fill();
});
}
}
// ======================================================
// Merge (Space), Detach (CTRL+Space), Straighten (Shift+Space)
// ======================================================
function pointLineDistance(P,A,B){
let ABx= B.x- A.x; let ABy= B.y- A.y;
let APx= P.x- A.x; let APy= P.y- A.y;
let ab2= ABx*ABx+ ABy*ABy;
let t= (APx*ABx + APy*ABy)/ ab2;
if(t<0) t=0; if(t>1) t=1;
let px= A.x+ t*ABx; let py= A.y+ t*ABy;
return dist(P,{ x:px,y:py });
}
function projectPointOntoLine(P,A,B){
let ABx= B.x- A.x; let ABy= B.y- A.y;
let APx= P.x- A.x; let APy= P.y- A.y;
let ab2= ABx*ABx+ ABy*ABy;
let t= (APx*ABx + APy*ABy)/ ab2;
if(t<0) t=0; if(t>1) t=1;
return { x: A.x+ t*ABx, y: A.y+ t*ABy };
}
function splitLine(line, proj){
let { start, end }= line;
let epProj= getSnappedEndpoint(proj.x, proj.y);
if(dist(epProj,start)<1e-6|| dist(epProj,end)<1e-6) return;
let i1= start.lines.indexOf(line);
if(i1>-1) start.lines.splice(i1,1);
let i2= end.lines.indexOf(line);
if(i2>-1) end.lines.splice(i2,1);
let i3= lines.indexOf(line);
if(i3>-1) lines.splice(i3,1);
let ln1= new Line(start, epProj);
let ln2= new Line(epProj, end);
lines.push(ln1, ln2);
cleanupEndpoints();
}
/**
* Merge logic (Space) with additional step:
* If there are multiple endpoints at the same location as ep,
* unify them as well (or near enough within threshold).
*/
function spaceMergeDownHoveredEndpoint(ep){
const threshold=10;
// Step 1: unify other endpoints that are at the same location or within threshold
// We do a pass to find all endpoints within threshold of ep
let toUnify= endpoints.filter( ept=> ept!== ep && dist(ept, ep)<= threshold );
toUnify.forEach( ept=>{
// merge ept => ep
ept.lines.forEach( ln=>{
if(ln.start=== ept){
ln.start= ep;
if(!ep.lines.includes(ln)) ep.lines.push(ln);
}
if(ln.end=== ept){
ln.end= ep;
if(!ep.lines.includes(ln)) ep.lines.push(ln);
}
});
let idx= endpoints.indexOf(ept);
if(idx>-1) endpoints.splice(idx,1);
});
// Step 2: attempt the "old" line merging logic
// (i.e. if ep is near a line, project and unify)
for(let line of lines){
if(line.start=== ep|| line.end=== ep) continue;
let d= pointLineDistance(ep, line.start, line.end);
if(d<= threshold){
let proj= projectPointOntoLine(ep, line.start, line.end);
if(dist(proj, line.start)>1e-6 && dist(proj, line.end)>1e-6){
splitLine(line, proj);
}
let target= findEndpoint(proj.x, proj.y);
if(target && target!== ep){
// unify ep => target
ep.lines.forEach(ln=>{
if(ln.start=== ep){
ln.start= target;
if(!target.lines.includes(ln)) target.lines.push(ln);
}
if(ln.end=== ep){
ln.end= target;
if(!target.lines.includes(ln)) target.lines.push(ln);
}
});
let idx= endpoints.indexOf(ep);
if(idx>-1) endpoints.splice(idx,1);
} else {
ep.x= proj.x;
ep.y= proj.y;
}
cleanupEndpoints();
draw();
return;
}
}
cleanupEndpoints();
draw();
}
// forcibly create new endpoints for each line referencing ep => remove ep
function detachHoveredEndpoint(ep){
if(!ep) return;
let linesCopy= ep.lines.slice();
for(let ln of linesCopy){
let newEp= { x: ep.x, y: ep.y, lines:[], selected:false };
endpoints.push(newEp);
if(ln.start=== ep){
ln.start= newEp;
newEp.lines.push(ln);
} else if(ln.end=== ep){
ln.end= newEp;
newEp.lines.push(ln);
}
}
let idx= endpoints.indexOf(ep);
if(idx>-1) endpoints.splice(idx,1);
cleanupEndpoints();
draw();
}
// chain BFS => best-fit line
function straightenChain(ep){
if(!ep) return;
let chain= findChainEndpoints(ep);
if(chain.length<2) return;
let sumX=0, sumY=0;
chain.forEach(p=> { sumX+= p.x; sumY+= p.y; });
let meanX= sumX/ chain.length;
let meanY= sumY/ chain.length;
let num=0, den=0;
chain.forEach(p=>{
let dx= p.x- meanX;
let dy= p.y- meanY;
num+= dx*dy;
den+= dx*dx;
});
let slope;
if(Math.abs(den)<1e-12) slope= null; // vertical
else slope= num/ den;
if(slope=== null){
chain.forEach(p=> p.x= meanX);
} else {
let c= meanY - slope* meanX;
chain.forEach(p=>{
let x0= p.x, y0= p.y;
let m= slope;
let d= (x0 + (y0- c)* m)/(1+ m*m);
p.x= d;
p.y= m*d+ c;
});
}
cleanupEndpoints();
draw();
}
// ======================================================
// Undo/Redo
// ======================================================
function snapshot(){
let endpointsData= endpoints.map(ep=>({
x: ep.x, y: ep.y, selected: ep.selected|| false
}));
let linesData= lines.map(ln=>({
startIndex: endpoints.indexOf(ln.start),
endIndex: endpoints.indexOf(ln.end)
}));
let circlesData= circles.map(circle=>({
centerIndex: endpoints.indexOf(circle.center),
radius: circle.radius,
samplePoints: circle.samplePoints.map(sp=>({
x: sp.x,y: sp.y, selected: sp.selected|| false
}))
}));
return { endpointsData, linesData, circlesData };
}
function restoreSnapshot(snap){
endpoints.length=0;
lines.length=0;
circles.length=0;
snap.endpointsData.forEach(ed=>{
endpoints.push({ x: ed.x, y: ed.y, lines:[], selected: ed.selected });
});
snap.linesData.forEach(ld=>{
let sEp= endpoints[ld.startIndex];
let eEp= endpoints[ld.endIndex];
if(!sEp|| !eEp) return;
let ln= new Line(sEp,eEp);
lines.push(ln);
});
snap.circlesData.forEach(cd=>{
let centerEp= endpoints[cd.centerIndex];
if(!centerEp) return;
let circ= new Circle(centerEp, cd.radius);
circ.samplePoints.length=0;
cd.samplePoints.forEach(sp=>{
let spt= { x: sp.x,y: sp.y, lines:[], selected: sp.selected, parentCircle: circ };
circ.samplePoints.push(spt);
endpoints.push(spt);
});
circles.push(circ);
});
cleanupEndpoints();
draw();
}
function pushSnapshot(){
let data= snapshot();
undoStack.push(data);
redoStack.length=0;
}
function undo(){
if(undoStack.length<2) return;
undoStack.pop();
let data= undoStack[undoStack.length-1];
restoreSnapshot(data);
}
function redo(){
if(redoStack.length===0) return;
let data= redoStack.pop();
let current= snapshot();
undoStack.push(current);
restoreSnapshot(data);
}
// ======================================================
// Draw
// ======================================================
function drawGrid(){
if(!labelsVisible) return;
ctx.strokeStyle="#ddd";
ctx.lineWidth=1;
let leftX= -panOffset.x;
let topY= -panOffset.y;
let rightX= leftX + canvas.width;
let bottomY= topY + canvas.height;
let startX= Math.floor(leftX/ pxPerCm)* pxPerCm;
let startY= Math.floor(topY / pxPerCm)* pxPerCm;
let endX= Math.ceil(rightX/ pxPerCm)* pxPerCm;
let endY= Math.ceil(bottomY/ pxPerCm)* pxPerCm;
for(let x= startX; x<= endX; x+= pxPerCm){
ctx.beginPath();
ctx.moveTo(x, startY);
ctx.lineTo(x, endY);
ctx.stroke();
}
for(let y= startY; y<= endY; y+= pxPerCm){
ctx.beginPath();
ctx.moveTo(startX, y);
ctx.lineTo(endX, y);
ctx.stroke();
}
}
function drawVertexAngles(){
if(!showAngles) return;
const arcRadius=20;
endpoints.forEach(ep=>{
if(ep.lines.length>=2){
let angles= ep.lines.map(ln=>{
let other= (ln.start=== ep)? ln.end: ln.start;
let a= Math.atan2(other.y- ep.y, other.x- ep.x);
if(a<0) a+= 2*Math.PI;
return a;
});
angles.sort((a,b)=> a-b);
for(let i=0;i< angles.length;i++){
let a1= angles[i];
let a2= (i=== angles.length-1)? angles[0]+ 2*Math.PI : angles[i+1].valueOf();
let gap= a2- a1;
if(gap<0) gap+= 2*Math.PI;
if(gap> (5*Math.PI/180) && gap< Math.PI){
ctx.beginPath();
ctx.strokeStyle="rgba(0,0,255,0.7)";
ctx.arc(ep.x, ep.y, arcRadius, a1, a1+ gap);
ctx.stroke();
let mid= a1+ gap/2;
let tx= ep.x+ (arcRadius+10)* Math.cos(mid);
let ty= ep.y+ (arcRadius+10)* Math.sin(mid);
ctx.save();
ctx.font="12px Arial";
ctx.fillStyle="rgba(0,0,0,0.9)";
ctx.fillText((gap*180/Math.PI).toFixed(1)+"°", tx, ty);
ctx.restore();
}
}
}
});
}
function drawExtraLineLabels(){
if(!showLineLengths) return;
ctx.save();
ctx.font="12px Arial";
ctx.fillStyle="green";
lines.forEach(ln=>{
let midX= (ln.start.x+ ln.end.x)/2;
let midY= (ln.start.y+ ln.end.y)/2;
ctx.fillText(ln.length.toFixed(2)+" cm", midX, midY);
});
ctx.restore();
}
function drawPreviewLabel(){
if(!startEndpoint|| !currentPosLine|| !labelsVisible) return;
let dx= currentPosLine.x- startEndpoint.x;
let dy= currentPosLine.y- startEndpoint.y;
let lenCm= (Math.hypot(dx,dy)/ pxPerCm).toFixed(2);
let angleDeg= (Math.atan2(dy,dx)* 180/ Math.PI).toFixed(1);
let label= "";
if(showAngles && !showLineLengths) label= "Angle: "+ angleDeg+"°";
else if(showLineLengths && !showAngles) label= "Length: "+ lenCm+" cm";
else label= "Angle: "+ angleDeg+"° | "+ lenCm+" cm";
ctx.save();
ctx.font="12px Arial";
ctx.fillStyle="rgba(0,0,0,0.8)";
ctx.fillText(label, currentPosLine.x+10, currentPosLine.y-10);
ctx.restore();
}
function drawPreviewCircleLabel(center, radius){
if(!center|| !radius|| !labelsVisible) return;
let lenCm= (radius/ pxPerCm).toFixed(2);
let label= "Radius: "+ lenCm+" cm";
ctx.save();
ctx.font="12px Arial";
ctx.fillStyle="rgba(0,0,0,0.8)";
ctx.fillText(label, center.x+ radius+ 10, center.y- 10);
ctx.restore();
}
function drawSelectionRectangle(){
if(!isSelecting|| !selectionStart|| !selectionCurrent|| !labelsVisible) return;
ctx.save();
ctx.strokeStyle="rgba(0,191,255,0.8)";
ctx.lineWidth=1;
ctx.setLineDash([4,4]);
let x= Math.min(selectionStart.x, selectionCurrent.x);
let y= Math.min(selectionStart.y, selectionCurrent.y);
let w= Math.abs(selectionStart.x- selectionCurrent.x);
let h= Math.abs(selectionStart.y- selectionCurrent.y);
ctx.strokeRect(x,y,w,h);
ctx.restore();
}
function draw(){
ctx.clearRect(0,0, canvas.width, canvas.height);
ctx.save();
ctx.translate(-panOffset.x, -panOffset.y);
// grid
drawGrid();
lines.forEach(ln=> ln.draw());
circles.forEach(circle=> circle.draw());
if(labelsVisible){
endpoints.forEach(ep=>{
if(ep.matchHover){
ctx.strokeStyle="#00FFFF";
ctx.lineWidth=3;
ctx.beginPath();
ctx.arc(ep.x, ep.y,10,0,2*Math.PI);
ctx.stroke();
}
if(ep=== hoverEndpoint){
ctx.strokeStyle="orange";
ctx.lineWidth=4;
ctx.beginPath();
ctx.arc(ep.x,ep.y,8,0,2*Math.PI);
ctx.stroke();
}
if(ep.selected){
ctx.fillStyle="#800080";
} else {
if(ep.lines.length<2) ctx.fillStyle="#00FF00";
else ctx.fillStyle="#FF0000";
}
ctx.beginPath();
ctx.arc(ep.x, ep.y,6,0,2*Math.PI);
ctx.fill();
});
}
drawVertexAngles();
drawExtraLineLabels();
if(isSelecting) drawSelectionRectangle();
if(isDrawingLine && startEndpoint && currentPosLine){
ctx.strokeStyle="#aaa";
ctx.lineWidth=2;
ctx.setLineDash([5,3]);
ctx.beginPath();
ctx.moveTo(startEndpoint.x, startEndpoint.y);
ctx.lineTo(currentPosLine.x, currentPosLine.y);
ctx.stroke();
ctx.setLineDash([]);
drawPreviewLabel();
}
if(isDrawingCircle && circleCenter && currentPosCircle){
let radius= dist(circleCenter, currentPosCircle);
ctx.strokeStyle="#aaa";
ctx.lineWidth=2;
ctx.setLineDash([5,3]);
ctx.beginPath();
ctx.arc(circleCenter.x, circleCenter.y, radius,0,2*Math.PI);
ctx.stroke();
ctx.setLineDash([]);
drawPreviewCircleLabel(circleCenter, radius);
}
ctx.restore();
}
// ======================================================
// Mouse
// ======================================================
canvas.addEventListener("mousedown", e=>{
if(e.button===1){
isPanning= true;
panStart= { x:e.clientX, y:e.clientY };
oldPan= { x: panOffset.x, y: panOffset.y };
return;
}
let pos= getMousePos(e);
// SHIFT+Right => toggle multi-select
if(e.button===2 && e.shiftKey && !e.ctrlKey && !e.altKey){
let ep= findEndpoint(pos.x,pos.y);
if(ep){
ep.selected= !ep.selected;
draw();
}
return;
}
// Right => single select
if(e.button===2 && !e.shiftKey && !e.ctrlKey && !e.altKey){
endpoints.forEach(ep=> ep.selected= false);
let ep= findEndpoint(pos.x,pos.y);
if(ep) ep.selected= true;
draw();
return;
}
// CTRL+ALT+Right => selection rect
if(e.button===2 && e.ctrlKey && e.altKey){
isSelecting= true;
selectionStart= pos;
selectionCurrent= pos;
draw();
return;
}
// If “V” => circle, else line
if(e.button===0 && !e.ctrlKey && !e.altKey){
if(vKeyHeld){
isDrawingCircle= true;
circleCenter= findEndpoint(pos.x,pos.y) || getSnappedEndpoint(pos.x,pos.y);
currentPosCircle= { x: pos.x,y: pos.y };
pushSnapshot();
draw();
return;
} else {
isDrawingLine= true;
startEndpoint= findEndpoint(pos.x,pos.y) || getSnappedEndpoint(pos.x,pos.y);
currentPosLine= { x: pos.x,y: pos.y };
pushSnapshot();
draw();
return;
}
}
// CTRL+Left => drag endpoint
if(e.button===0 && e.ctrlKey && !e.altKey){
let ep= findEndpoint(pos.x,pos.y);
if(ep){
if(ep.selected){
isDraggingEndpoint= true;
draggedEndpoints= endpoints.filter(ept=> ept.selected);
} else {
isDraggingEndpoint= true;
draggedEndpoints=[ ep ];
}
dragStartPos= pos;
endpointsOriginalPos= draggedEndpoints.map(ept=> ({ ept, x:ept.x,y:ept.y }));
pushSnapshot();
draw();
return;
}
}
});
canvas.addEventListener("mousemove", e=>{
if(isPanning){
let dx= e.clientX- panStart.x;
let dy= e.clientY- panStart.y;
panOffset.x= oldPan.x- dx;
panOffset.y= oldPan.y- dy;
draw();
return;
}
let pos= getMousePos(e);
if(isSelecting){
selectionCurrent= pos;
draw();
return;
}
if(isDraggingEndpoint && draggedEndpoints.length>0){
let dx= pos.x- dragStartPos.x;
let dy= pos.y- dragStartPos.y;
draggedEndpoints.forEach(ept=>{
let orig= endpointsOriginalPos.find(o=> o.ept=== ept);
if(orig){
let newPos= { x: orig.x+ dx, y: orig.y+ dy };
if(e.shiftKey && ept.lines.length>0){
newPos= applyConstraints({ x: orig.x,y: orig.y, lines:ept.lines }, newPos,true);
}
newPos= snapDraggedEndpoint(newPos, draggedEndpoints);
ept.x= newPos.x;
ept.y= newPos.y;
}
});
endpoints.forEach(ep=>{
if(!draggedEndpoints.includes(ep)){
if(draggedEndpoints.some(de=> dist(ep,de)< snapRadius)) ep.matchHover= true;
else delete ep.matchHover;
}
});
draggedEndpoints.forEach(ept=>{
ept.lines.forEach(ln=>{
ln.length= dist(ln.start, ln.end)/ pxPerCm;
});
});
draw();
return;
}
if(isDrawingLine){
let posC= applyConstraints(startEndpoint, pos, e.shiftKey);
if(e.shiftKey && hoverEndpoint && hoverEndpoint!== startEndpoint){
let angle= Math.atan2(hoverEndpoint.y- startEndpoint.y, hoverEndpoint.x- startEndpoint.x);
let distance= Math.hypot(pos.x- startEndpoint.x, pos.y- startEndpoint.y);
posC= { x: startEndpoint.x+ distance* Math.cos(angle), y: startEndpoint.y+ distance*Math.sin(angle) };
}
currentPosLine= { x: posC.x, y: posC.y };
draw();
return;
}
if(isDrawingCircle){
currentPosCircle= { x: pos.x, y: pos.y };
draw();
return;
}
if(!isDraggingEndpoint && !isDrawingLine && !isDrawingCircle && !isSelecting){
let newHover= null;
for(let ep of endpoints){
if(dist(ep,pos)<= snapRadius){
newHover= ep;
break;
}
}
hoverEndpoint= newHover;
} else {
hoverEndpoint= null;
}
if(!isDraggingEndpoint){
endpoints.forEach(ep=> delete ep.matchHover);
}
draw();
});
canvas.addEventListener("mouseup", e=>{
if(isPanning && e.button===1){
isPanning= false;
return;
}
let pos= getMousePos(e);
if(isSelecting){
endpoints.forEach(ep=>{
if(pointInRect(ep, selectionStart, selectionCurrent)){
ep.selected= !ep.selected;
}
});
isSelecting= false;
selectionStart= selectionCurrent= null;
draw();
return;
}
if(isDraggingEndpoint && draggedEndpoints.length>0){
draggedEndpoints.forEach(dep=>{
let near= endpoints.find(ep=> !draggedEndpoints.includes(ep) && dist(dep,ep)<= snapRadius );
if(near){
dep.lines.forEach(ln=>{
if(ln.start=== dep){
ln.start= near;
if(!near.lines.includes(ln)) near.lines.push(ln);
}
if(ln.end=== dep){
ln.end= near;
if(!near.lines.includes(ln)) near.lines.push(ln);
}
});
let idx= endpoints.indexOf(dep);
if(idx>-1) endpoints.splice(idx,1);
}
});
isDraggingEndpoint= false;
draggedEndpoints= [];
endpoints.forEach(ep=> delete ep.matchHover);
cleanupEndpoints();
draw();
return;
}
if(isDrawingLine){
let finalPos= applyConstraints(startEndpoint, pos, e.shiftKey);
let endEp= findEndpoint(finalPos.x, finalPos.y) || getSnappedEndpoint(finalPos.x, finalPos.y);
if(startEndpoint.x=== endEp.x && startEndpoint.y=== endEp.y){
isDrawingLine= false;
draw();
return;
}
if(!lineExists(startEndpoint, endEp)){
let newLine= new Line(startEndpoint, endEp);
lines.push(newLine);
}
isDrawingLine= false;
draw();
return;
}
if(isDrawingCircle){
let radius= dist(circleCenter, pos);
if(radius<5){
isDrawingCircle= false;
draw();
return;
}
let newCircle= new Circle(circleCenter, radius);
circles.push(newCircle);
isDrawingCircle= false;
draw();
return;
}
});
// ======================================================
// Keyboard
// ======================================================
window.addEventListener("keydown", e=>{
if(e.key==="Shift"){
shiftIsHeld= true;
draw();
}
if(e.key.toLowerCase()==="h"){
labelsVisible= !labelsVisible;
draw();
}
if(e.key.toLowerCase()==="i"){
showAngles= !showAngles;
draw();
}
if(e.ctrlKey && e.key.toLowerCase()==="a"){
e.preventDefault();
endpoints.forEach(ep=> ep.selected= true);
draw();
}
if(e.key==="Escape"){
endpoints.forEach(ep=> ep.selected= false);
draw();
}
if(e.key.toLowerCase()==="v"){
vKeyHeld= true;
draw();
}
// SHIFT+SPACE => straighten chain
if(e.key===" " && e.shiftKey && !e.ctrlKey){
if(hoverEndpoint){
pushSnapshot();
straightenChain(hoverEndpoint);
e.preventDefault();
}
}
// SPACE => merge
if(e.key===" " && !e.shiftKey && !e.ctrlKey){
if(hoverEndpoint){
pushSnapshot();
spaceMergeDownHoveredEndpoint(hoverEndpoint);
e.preventDefault();
}
}
// CTRL+SPACE => detach
if(e.key===" " && e.ctrlKey && !e.shiftKey){
if(hoverEndpoint){
pushSnapshot();
detachHoveredEndpoint(hoverEndpoint);
e.preventDefault();
draw();
}
}
// CTRL+S => save
if(e.ctrlKey && e.key.toLowerCase()==="s"){
e.preventDefault();
pushSnapshot();
saveProject();
}
// CTRL+L => load
if(e.ctrlKey && e.key.toLowerCase()==="l"){
e.preventDefault();
pushSnapshot();
loadProject();
}
// CTRL+P => PNG
if(e.ctrlKey && e.key.toLowerCase()==="p"){
e.preventDefault();
pushSnapshot();
savePNG();
}
// CTRL+Z => undo
if(e.ctrlKey && (e.key==="z" || e.key==="Z")){
e.preventDefault();
undo();
}
// CTRL+Y => redo
if(e.ctrlKey && (e.key==="y" || e.key==="Y")){
e.preventDefault();
redo();
}
if(e.key==="Delete"){
let circlesToRemove= new Set();
endpoints.forEach(ep=>{
if(ep.selected && ep.parentCircle) circlesToRemove.add(ep.parentCircle);
});
circlesToRemove.forEach(circle=> removeCircle(circle));
for(let i=endpoints.length-1;i>=0;i--){
if(endpoints[i].selected){
endpoints[i].lines.forEach(ln=>{
let idx= lines.indexOf(ln);
if(idx>-1) lines.splice(idx,1);
});
endpoints.splice(i,1);
}
}
cleanupEndpoints();
draw();
}
// “U” => toggles line lengths
if(e.key.toLowerCase()==="u"){
showLineLengths= !showLineLengths;
e.preventDefault();
draw();
}
});
window.addEventListener("keyup", e=>{