-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1785 lines (1537 loc) · 76.1 KB
/
script.js
File metadata and controls
1785 lines (1537 loc) · 76.1 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
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
class WhiteboardApp {
constructor() {
this.canvas = document.getElementById('canvas');
this.ctx = this.canvas.getContext('2d');
this.canvasContainer = document.getElementById('canvasContainer');
this.saveBtn = document.getElementById('saveBtn');
// Enhanced canvas state
this.zoom = 1;
this.panX = 0;
this.panY = 0;
this.isPanning = false;
this.isSpacePanning = false;
this.spacePressed = false;
// Enhanced drawing state
this.isDrawing = false;
this.isSelecting = false;
this.isDragging = false;
this.startX = 0;
this.startY = 0;
this.currentX = 0;
this.currentY = 0;
this.lastX = 0;
this.lastY = 0;
// Smooth drawing
this.smoothing = true;
this.smoothingFactor = 0.3;
// Tools and settings
this.currentTool = 'pen';
this.strokeColor = '#000000';
this.backgroundColor = '#ffffff';
this.strokeWidth = 2;
this.isDarkTheme = false;
this.selectedFont = 'Arial';
this.fontSize = 16;
// Data storage
this.shapes = [];
this.undoStack = [];
this.redoStack = [];
this.currentPath = [];
this.hasUnsavedChanges = false;
// Selection system
this.selectedShapes = [];
this.selectionBox = null;
this.isResizing = false;
this.resizeHandle = null;
// Text input
this.activeTextInput = null;
// Enhanced pointer tracking
this.pointerCache = [];
this.lastPointerTime = 0;
this.init();
}
init() {
this.resizeCanvas();
this.setupEventListeners();
this.setupToolbar();
this.updateCanvasBackground();
this.saveState();
this.redraw();
// Enhanced canvas settings for smooth rendering
this.ctx.lineCap = 'round';
this.ctx.lineJoin = 'round';
this.ctx.imageSmoothingEnabled = true;
this.ctx.imageSmoothingQuality = 'high';
}
resizeCanvas() {
const rect = this.canvasContainer.getBoundingClientRect();
const dpr = window.devicePixelRatio || 1;
this.canvas.width = rect.width * dpr;
this.canvas.height = rect.height * dpr;
this.canvas.style.width = rect.width + 'px';
this.canvas.style.height = rect.height + 'px';
this.ctx.scale(dpr, dpr);
this.redraw();
}
setupEventListeners() {
// Resize
window.addEventListener('resize', () => this.resizeCanvas());
// Enhanced pointer events with better tracking
this.canvas.addEventListener('pointerdown', (e) => this.handlePointerDown(e));
this.canvas.addEventListener('pointermove', (e) => this.handlePointerMove(e));
this.canvas.addEventListener('pointerup', (e) => this.handlePointerUp(e));
this.canvas.addEventListener('pointerout', (e) => this.handlePointerUp(e));
this.canvas.addEventListener('pointercancel', (e) => this.handlePointerUp(e));
// Prevent default touch behaviors
this.canvas.addEventListener('touchstart', (e) => e.preventDefault());
this.canvas.addEventListener('touchmove', (e) => e.preventDefault());
this.canvas.addEventListener('touchend', (e) => e.preventDefault());
// Enhanced wheel handling
this.canvas.addEventListener('wheel', (e) => this.handleWheel(e), { passive: false });
// Double click for text
this.canvas.addEventListener('dblclick', (e) => this.handleDoubleClick(e));
// Enhanced keyboard shortcuts
document.addEventListener('keydown', (e) => this.handleKeyDown(e));
document.addEventListener('keyup', (e) => this.handleKeyUp(e));
// Zoom and save controls
document.getElementById('zoomInBtn').addEventListener('click', () => this.zoomIn());
document.getElementById('zoomOutBtn').addEventListener('click', () => this.zoomOut());
this.saveBtn.addEventListener('click', () => this.exportImage());
// Prevent context menu and text selection during drawing
this.canvas.addEventListener('contextmenu', (e) => e.preventDefault());
this.canvas.addEventListener('selectstart', (e) => e.preventDefault());
// Enhanced window focus handling
window.addEventListener('blur', () => {
this.spacePressed = false;
this.isSpacePanning = false;
this.isPanning = false;
this.isDrawing = false;
});
// Global pointer tracking to handle cursor leaving canvas
document.addEventListener('pointermove', (e) => {
if (this.isDrawing || this.isPanning || this.isSpacePanning) {
this.handleGlobalPointerMove(e);
}
});
document.addEventListener('pointerup', (e) => {
if (this.isDrawing || this.isPanning || this.isSpacePanning) {
this.handlePointerUp(e);
}
});
}
handleGlobalPointerMove(e) {
// Continue drawing/panning even when cursor leaves canvas
const rect = this.canvas.getBoundingClientRect();
const isOverCanvas = (
e.clientX >= rect.left &&
e.clientX <= rect.right &&
e.clientY >= rect.top &&
e.clientY <= rect.bottom
);
if (!isOverCanvas) {
// Clamp coordinates to canvas bounds
const clampedX = Math.max(rect.left, Math.min(rect.right, e.clientX));
const clampedY = Math.max(rect.top, Math.min(rect.bottom, e.clientY));
const clampedEvent = {
...e,
clientX: clampedX,
clientY: clampedY
};
this.handlePointerMove(clampedEvent);
}
}
setupToolbar() {
// Tool buttons
document.querySelectorAll('.tool-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
const tool = e.target.dataset.tool;
this.setTool(tool);
});
});
// Theme buttons
document.querySelectorAll('.theme-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
const theme = e.target.dataset.theme;
this.setTheme(theme);
});
});
// Color pickers
document.getElementById('colorPicker').addEventListener('change', (e) => {
this.strokeColor = e.target.value;
this.updateSelectedShapesColor();
});
document.getElementById('bgPicker').addEventListener('change', (e) => {
this.backgroundColor = e.target.value;
this.updateCanvasBackground();
this.updateToolbarTheme();
});
// Stroke width slider
document.getElementById('strokeWidth').addEventListener('input', (e) => {
this.strokeWidth = parseInt(e.target.value);
document.getElementById('widthValue').textContent = this.strokeWidth;
this.updateSelectedShapesWidth();
});
// Font controls
document.getElementById('fontSelector').addEventListener('change', (e) => {
this.selectedFont = e.target.value;
});
document.getElementById('fontSizeInput').addEventListener('change', (e) => {
this.fontSize = parseInt(e.target.value);
});
}
updateToolbarTheme() {
const toolbar = document.querySelector('.toolbar');
const brightness = this.getBrightness(this.backgroundColor);
if (brightness < 128) {
toolbar.style.background = 'rgba(255, 255, 255, 0.95)';
toolbar.style.color = '#000';
} else {
toolbar.style.background = 'rgba(30, 30, 50, 0.95)';
toolbar.style.color = '#fff';
}
}
getBrightness(color) {
const hex = color.replace('#', '');
const r = parseInt(hex.substr(0, 2), 16);
const g = parseInt(hex.substr(2, 2), 16);
const b = parseInt(hex.substr(4, 2), 16);
return (r * 299 + g * 587 + b * 114) / 1000;
}
setTool(tool) {
this.currentTool = tool;
this.clearSelection();
document.querySelectorAll('.tool-btn').forEach(btn => {
btn.classList.remove('active');
if (btn.dataset.tool === tool) {
btn.classList.add('active');
}
});
// Show/hide text controls
const textControls = document.getElementById('textControls');
if (textControls) {
textControls.style.display = tool === 'text' ? 'flex' : 'none';
}
// Update cursor
this.canvas.style.cursor = this.getCursorForTool();
// Clear text input if switching tools
if (tool !== 'text' && this.activeTextInput) {
this.finalizeTextInput();
}
this.redraw();
}
getCursorForTool() {
if (this.spacePressed) return 'grab';
const cursors = {
pen: 'crosshair',
eraser: 'crosshair',
select: 'default',
rectangle: 'crosshair',
circle: 'crosshair',
line: 'crosshair',
arrow: 'crosshair',
text: 'text'
};
return cursors[this.currentTool] || 'default';
}
setTheme(theme) {
this.isDarkTheme = theme === 'dark';
document.body.className = this.isDarkTheme ? 'dark-theme' : '';
document.querySelectorAll('.theme-btn').forEach(btn => {
btn.classList.remove('active');
if (btn.dataset.theme === theme) {
btn.classList.add('active');
}
});
this.updateCanvasBackground();
}
updateCanvasBackground() {
this.canvasContainer.style.backgroundColor = this.backgroundColor;
}
showSaveButton() {
this.saveBtn.classList.add('visible');
this.hasUnsavedChanges = true;
}
hideSaveButton() {
this.saveBtn.classList.remove('visible');
this.hasUnsavedChanges = false;
}
handleKeyDown(e) {
// Space for panning
if (e.code === 'Space' && !this.spacePressed && !this.activeTextInput) {
e.preventDefault();
this.spacePressed = true;
this.canvas.style.cursor = 'grab';
return;
}
if (e.ctrlKey || e.metaKey) {
switch (e.key.toLowerCase()) {
case 'z':
e.preventDefault();
if (e.shiftKey) {
this.redo();
} else {
this.undo();
}
break;
case 'y':
e.preventDefault();
this.redo();
break;
case 's':
e.preventDefault();
this.exportImage();
break;
case 'a':
e.preventDefault();
this.selectAll();
break;
case 'd':
e.preventDefault();
this.duplicateSelected();
break;
}
} else {
// Delete selected shapes
if ((e.key === 'Delete' || e.key === 'Backspace') && !this.activeTextInput) {
e.preventDefault();
this.deleteSelected();
}
// Tool shortcuts (only if not typing)
if (!this.activeTextInput) {
const toolMap = {
'p': 'pen',
'e': 'eraser',
'v': 'select',
'r': 'rectangle',
'c': 'circle',
'l': 'line',
'a': 'arrow',
't': 'text'
};
if (toolMap[e.key.toLowerCase()]) {
this.setTool(toolMap[e.key.toLowerCase()]);
}
}
}
}
handleKeyUp(e) {
if (e.code === 'Space') {
this.spacePressed = false;
this.isSpacePanning = false;
this.canvas.style.cursor = this.getCursorForTool();
}
}
handlePointerDown(e) {
e.preventDefault();
this.canvas.setPointerCapture(e.pointerId);
// Add drawing mode class to prevent text selection
document.body.classList.add('drawing-mode');
// Space panning
if (this.spacePressed) {
this.isSpacePanning = true;
this.lastPanX = e.clientX;
this.lastPanY = e.clientY;
this.canvas.style.cursor = 'grabbing';
return;
}
// Middle mouse or Ctrl+click for panning
if (e.button === 1 || (e.button === 0 && e.ctrlKey)) {
this.isPanning = true;
this.lastPanX = e.clientX;
this.lastPanY = e.clientY;
this.canvas.style.cursor = 'grabbing';
return;
}
const pos = this.getCanvasCoords(e.clientX, e.clientY);
// Check for resize handles first
if (this.currentTool === 'select' && this.selectedShapes.length > 0) {
const handle = this.getResizeHandle(pos.x, pos.y);
if (handle) {
this.isResizing = true;
this.resizeHandle = handle;
this.startX = pos.x;
this.startY = pos.y;
this.originalBounds = this.getSelectionBounds();
return;
}
}
this.isDrawing = true;
this.startX = pos.x;
this.startY = pos.y;
this.currentX = pos.x;
this.currentY = pos.y;
this.lastX = pos.x;
this.lastY = pos.y;
if (this.currentTool === 'pen') {
this.currentPath = [{x: pos.x, y: pos.y, pressure: e.pressure || 0.5}];
} else if (this.currentTool === 'eraser') {
this.eraseAt(pos.x, pos.y);
} else if (this.currentTool === 'select') {
// Check if clicking on existing shape
const clicked = this.getShapeAt(pos.x, pos.y);
if (clicked && !e.shiftKey) {
if (!this.selectedShapes.includes(clicked)) {
this.selectedShapes = [clicked];
}
this.isDragging = true;
this.dragStartX = pos.x;
this.dragStartY = pos.y;
} else if (clicked && e.shiftKey) {
// Add to selection
if (this.selectedShapes.includes(clicked)) {
this.selectedShapes = this.selectedShapes.filter(s => s !== clicked);
} else {
this.selectedShapes.push(clicked);
}
} else {
// Start selection box
this.clearSelection();
this.startSelection(pos.x, pos.y);
this.isSelecting = true;
}
}
this.lastPointerTime = performance.now();
}
handlePointerMove(e) {
e.preventDefault();
const currentTime = performance.now();
const deltaTime = currentTime - this.lastPointerTime;
// Space panning
if (this.isSpacePanning) {
const deltaX = e.clientX - this.lastPanX;
const deltaY = e.clientY - this.lastPanY;
this.panX += deltaX / this.zoom;
this.panY += deltaY / this.zoom;
this.lastPanX = e.clientX;
this.lastPanY = e.clientY;
this.redraw();
return;
}
// Regular panning
if (this.isPanning) {
const deltaX = e.clientX - this.lastPanX;
const deltaY = e.clientY - this.lastPanY;
this.panX += deltaX / this.zoom;
this.panY += deltaY / this.zoom;
this.lastPanX = e.clientX;
this.lastPanY = e.clientY;
this.redraw();
return;
}
const pos = this.getCanvasCoords(e.clientX, e.clientY);
// Handle resize
if (this.isResizing && this.resizeHandle) {
this.handleResize(pos.x, pos.y);
return;
}
// Update cursor for resize handles
if (this.currentTool === 'select' && this.selectedShapes.length > 0 && !this.isDrawing) {
const handle = this.getResizeHandle(pos.x, pos.y);
if (handle) {
this.canvas.style.cursor = this.getResizeCursor(handle);
} else {
this.canvas.style.cursor = 'default';
}
}
if (!this.isDrawing) return;
this.currentX = pos.x;
this.currentY = pos.y;
if (this.currentTool === 'select') {
if (this.isDragging) {
// Drag selected shapes
const deltaX = pos.x - this.dragStartX;
const deltaY = pos.y - this.dragStartY;
this.moveSelectedShapes(deltaX, deltaY);
this.dragStartX = pos.x;
this.dragStartY = pos.y;
} else if (this.isSelecting) {
this.updateSelection();
}
} else if (this.currentTool === 'pen') {
// Enhanced smooth drawing
if (deltaTime > 16) { // Throttle to ~60fps
const distance = Math.sqrt(
Math.pow(pos.x - this.lastX, 2) + Math.pow(pos.y - this.lastY, 2)
);
if (distance > 1) {
// Add interpolated points for smoother curves
if (this.smoothing && distance > 3) {
const steps = Math.ceil(distance / 2);
for (let i = 1; i <= steps; i++) {
const t = i / steps;
const smoothX = this.lastX + (pos.x - this.lastX) * t;
const smoothY = this.lastY + (pos.y - this.lastY) * t;
this.currentPath.push({
x: smoothX,
y: smoothY,
pressure: e.pressure || 0.5
});
}
} else {
this.currentPath.push({
x: pos.x,
y: pos.y,
pressure: e.pressure || 0.5
});
}
this.lastX = pos.x;
this.lastY = pos.y;
this.redrawWithPreview();
}
this.lastPointerTime = currentTime;
}
} else if (this.currentTool === 'eraser') {
this.eraseAt(pos.x, pos.y);
} else if (['rectangle', 'circle', 'line', 'arrow'].includes(this.currentTool)) {
this.redrawWithPreview();
}
}
handlePointerUp(e) {
e.preventDefault();
// Remove drawing mode class
document.body.classList.remove('drawing-mode');
if (this.canvas.hasPointerCapture && e.pointerId) {
this.canvas.releasePointerCapture(e.pointerId);
}
if (this.isSpacePanning) {
this.isSpacePanning = false;
this.canvas.style.cursor = this.spacePressed ? 'grab' : this.getCursorForTool();
return;
}
if (this.isPanning) {
this.isPanning = false;
this.canvas.style.cursor = this.getCursorForTool();
return;
}
if (this.isResizing) {
this.isResizing = false;
this.resizeHandle = null;
this.saveState();
this.showSaveButton();
this.redraw();
return;
}
if (!this.isDrawing) return;
this.isDrawing = false;
this.isDragging = false;
this.isSelecting = false;
const pos = this.getCanvasCoords(e.clientX, e.clientY);
switch (this.currentTool) {
case 'pen':
if (this.currentPath.length > 1) {
this.shapes.push({
type: 'path',
points: [...this.currentPath],
color: this.strokeColor,
width: this.strokeWidth,
id: this.generateId(),
smooth: this.smoothing
});
this.saveState();
this.showSaveButton();
}
break;
case 'rectangle':
if (Math.abs(pos.x - this.startX) > 5 && Math.abs(pos.y - this.startY) > 5) {
this.shapes.push({
type: 'rectangle',
x: Math.min(this.startX, pos.x),
y: Math.min(this.startY, pos.y),
width: Math.abs(pos.x - this.startX),
height: Math.abs(pos.y - this.startY),
color: this.strokeColor,
strokeWidth: this.strokeWidth,
filled: false,
id: this.generateId()
});
this.saveState();
this.showSaveButton();
}
break;
case 'circle':
const radius = Math.sqrt(Math.pow(pos.x - this.startX, 2) + Math.pow(pos.y - this.startY, 2));
if (radius > 5) {
this.shapes.push({
type: 'circle',
x: this.startX,
y: this.startY,
radius: radius,
color: this.strokeColor,
strokeWidth: this.strokeWidth,
filled: false,
id: this.generateId()
});
this.saveState();
this.showSaveButton();
}
break;
case 'line':
if (Math.abs(pos.x - this.startX) > 5 || Math.abs(pos.y - this.startY) > 5) {
this.shapes.push({
type: 'line',
startX: this.startX,
startY: this.startY,
endX: pos.x,
endY: pos.y,
color: this.strokeColor,
strokeWidth: this.strokeWidth,
id: this.generateId()
});
this.saveState();
this.showSaveButton();
}
break;
case 'arrow':
if (Math.abs(pos.x - this.startX) > 5 || Math.abs(pos.y - this.startY) > 5) {
this.shapes.push({
type: 'arrow',
startX: this.startX,
startY: this.startY,
endX: pos.x,
endY: pos.y,
color: this.strokeColor,
strokeWidth: this.strokeWidth,
id: this.generateId()
});
this.saveState();
this.showSaveButton();
}
break;
case 'select':
if (this.selectionBox) {
this.finishSelection();
}
break;
}
this.redraw();
}
handleDoubleClick(e) {
if (this.currentTool === 'text' || this.currentTool === 'select') {
const pos = this.getCanvasCoords(e.clientX, e.clientY);
this.createTextInput(pos.x, pos.y);
}
}
handleWheel(e) {
e.preventDefault();
const rect = this.canvas.getBoundingClientRect();
const mouseX = e.clientX - rect.left;
const mouseY = e.clientY - rect.top;
const zoomFactor = e.deltaY > 0 ? 0.9 : 1.1;
const newZoom = Math.min(Math.max(this.zoom * zoomFactor, 0.1), 5);
if (newZoom !== this.zoom) {
const worldCoords = this.getCanvasCoords(e.clientX, e.clientY);
this.zoom = newZoom;
const newWorldCoords = this.getCanvasCoords(e.clientX, e.clientY);
this.panX += (worldCoords.x - newWorldCoords.x);
this.panY += (worldCoords.y - newWorldCoords.y);
this.updateZoomInfo();
this.redraw();
}
}
getCanvasCoords(clientX, clientY) {
const rect = this.canvas.getBoundingClientRect();
const x = (clientX - rect.left) / this.zoom - this.panX;
const y = (clientY - rect.top) / this.zoom - this.panY;
return { x, y };
}
// Selection system
startSelection(x, y) {
this.selectionBox = {
startX: x,
startY: y,
endX: x,
endY: y
};
}
updateSelection() {
if (this.selectionBox) {
this.selectionBox.endX = this.currentX;
this.selectionBox.endY = this.currentY;
this.redraw();
}
}
finishSelection() {
if (!this.selectionBox) return;
const box = this.selectionBox;
const minX = Math.min(box.startX, box.endX);
const maxX = Math.max(box.startX, box.endX);
const minY = Math.min(box.startY, box.endY);
const maxY = Math.max(box.startY, box.endY);
this.selectedShapes = this.shapes.filter(shape =>
this.isShapeInBounds(shape, minX, minY, maxX, maxY)
);
this.selectionBox = null;
}
isShapeInBounds(shape, minX, minY, maxX, maxY) {
switch (shape.type) {
case 'path':
return shape.points.some(point =>
point.x >= minX && point.x <= maxX &&
point.y >= minY && point.y <= maxY
);
case 'rectangle':
return !(shape.x > maxX || shape.x + shape.width < minX ||
shape.y > maxY || shape.y + shape.height < minY);
case 'circle':
return shape.x >= minX - shape.radius && shape.x <= maxX + shape.radius &&
shape.y >= minY - shape.radius && shape.y <= maxY + shape.radius;
case 'line':
case 'arrow':
return (shape.startX >= minX && shape.startX <= maxX &&
shape.startY >= minY && shape.startY <= maxY) ||
(shape.endX >= minX && shape.endX <= maxX &&
shape.endY >= minY && shape.endY <= maxY);
case 'text':
return shape.x >= minX && shape.x <= maxX &&
shape.y >= minY && shape.y <= maxY;
default:
return false;
}
}
getShapeAt(x, y) {
// Check in reverse order (top to bottom)
for (let i = this.shapes.length - 1; i >= 0; i--) {
if (this.isPointInShape(this.shapes[i], x, y)) {
return this.shapes[i];
}
}
return null;
}
isPointInShape(shape, x, y) {
const tolerance = 10 / this.zoom;
switch (shape.type) {
case 'path':
return shape.points.some(point =>
Math.abs(point.x - x) < tolerance && Math.abs(point.y - y) < tolerance
);
case 'rectangle':
return x >= shape.x - tolerance && x <= shape.x + shape.width + tolerance &&
y >= shape.y - tolerance && y <= shape.y + shape.height + tolerance;
case 'circle':
const dist = Math.sqrt(Math.pow(shape.x - x, 2) + Math.pow(shape.y - y, 2));
return Math.abs(dist - shape.radius) <= tolerance;
case 'line':
case 'arrow':
return this.distanceToLine(x, y, shape.startX, shape.startY, shape.endX, shape.endY) <= tolerance;
case 'text':
const textWidth = this.ctx.measureText(shape.text).width;
return x >= shape.x - tolerance && x <= shape.x + textWidth + tolerance &&
y >= shape.y - shape.fontSize && y <= shape.y + tolerance;
default:
return false;
}
}
distanceToLine(x, y, x1, y1, x2, y2) {
const A = x - x1;
const B = y - y1;
const C = x2 - x1;
const D = y2 - y1;
const dot = A * C + B * D;
const lenSq = C * C + D * D;
let param = -1;
if (lenSq !== 0) {
param = dot / lenSq;
}
let xx, yy;
if (param < 0) {
xx = x1;
yy = y1;
} else if (param > 1) {
xx = x2;
yy = y2;
} else {
xx = x1 + param * C;
yy = y1 + param * D;
}
const dx = x - xx;
const dy = y - yy;
return Math.sqrt(dx * dx + dy * dy);
}
clearSelection() {
this.selectedShapes = [];
this.selectionBox = null;
}
moveSelectedShapes(deltaX, deltaY) {
this.selectedShapes.forEach(shape => {
this.moveShape(shape, deltaX, deltaY);
});
this.redraw();
}
moveShape(shape, deltaX, deltaY) {
switch (shape.type) {
case 'path':
shape.points.forEach(point => {
point.x += deltaX;
point.y += deltaY;
});
break;
case 'rectangle':
case 'circle':
case 'text':
shape.x += deltaX;
shape.y += deltaY;
break;
case 'line':
case 'arrow':
shape.startX += deltaX;
shape.startY += deltaY;
shape.endX += deltaX;
shape.endY += deltaY;
break;
}
}
// Resize functionality
getResizeHandle(x, y) {
if (this.selectedShapes.length !== 1) return null;
const bounds = this.getSelectionBounds();
const handleSize = 8 / this.zoom;
const handles = [
{ name: 'nw', x: bounds.minX, y: bounds.minY },
{ name: 'ne', x: bounds.maxX, y: bounds.minY },
{ name: 'sw', x: bounds.minX, y: bounds.maxY },
{ name: 'se', x: bounds.maxX, y: bounds.maxY },
{ name: 'n', x: (bounds.minX + bounds.maxX) / 2, y: bounds.minY },
{ name: 's', x: (bounds.minX + bounds.maxX) / 2, y: bounds.maxY },
{ name: 'w', x: bounds.minX, y: (bounds.minY + bounds.maxY) / 2 },
{ name: 'e', x: bounds.maxX, y: (bounds.minY + bounds.maxY) / 2 }
];
return handles.find(handle =>
Math.abs(handle.x - x) <= handleSize && Math.abs(handle.y - y) <= handleSize
);
}
getSelectionBounds() {
if (this.selectedShapes.length === 0) return { minX: 0, minY: 0, maxX: 0, maxY: 0 };
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
this.selectedShapes.forEach(shape => {
const bounds = this.getShapeBounds(shape);
minX = Math.min(minX, bounds.minX);
minY = Math.min(minY, bounds.minY);
maxX = Math.max(maxX, bounds.maxX);
maxY = Math.max(maxY, bounds.maxY);
});
return { minX, minY, maxX, maxY };
}
getShapeBounds(shape) {
switch (shape.type) {
case 'rectangle':
return {
minX: shape.x,
minY: shape.y,
maxX: shape.x + shape.width,
maxY: shape.y + shape.height
};
case 'circle':
return {
minX: shape.x - shape.radius,
minY: shape.y - shape.radius,
maxX: shape.x + shape.radius,
maxY: shape.y + shape.radius
};
case 'line':
case 'arrow':
return {
minX: Math.min(shape.startX, shape.endX),
minY: Math.min(shape.startY, shape.endY),
maxX: Math.max(shape.startX, shape.endX),
maxY: Math.max(shape.startY, shape.endY)
};
case 'text':
const textWidth = shape.text ? shape.text.length * shape.fontSize * 0.6 : 100;
return {
minX: shape.x,
minY: shape.y - shape.fontSize,
maxX: shape.x + textWidth,
maxY: shape.y + 5
};
case 'path':
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
shape.points.forEach(point => {
minX = Math.min(minX, point.x);
minY = Math.min(minY, point.y);
maxX = Math.max(maxX, point.x);
maxY = Math.max(maxY, point.y);
});
return { minX, minY, maxX, maxY };
default:
return { minX: 0, minY: 0, maxX: 0, maxY: 0 };
}
}
getResizeCursor(handle) {
const cursors = {
'nw': 'nw-resize',
'ne': 'ne-resize',
'sw': 'sw-resize',
'se': 'se-resize',
'n': 'n-resize',
's': 's-resize',
'w': 'w-resize',