-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1905 lines (1602 loc) · 80.2 KB
/
Copy pathscript.js
File metadata and controls
1905 lines (1602 loc) · 80.2 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
// Global variables
let webcam, overlayCanvas, whiteboardCanvas;
let magnifierDiv, magnifierCanvas, magnifierCtx;
let overlayCtx; // whiteboardCtx removed as whiteboard is WebGL
let videoWidth, videoHeight;
let trapezoidPoints = [];
let isWhiteboardMode = false;
let gl, program;
let positionLocation, texCoordLocation;
let matrixLocation, resolutionLocation;
let currentPerspectiveMatrix = null; // To store the calculated perspective matrix
let currentSrcPoints = null; // To store the source points for logging
let positionBuffer = null; // WebGL buffer for vertex positions
let texCoordBuffer = null; // WebGL buffer for texture coordinates
let isVideoHoldActive = false;
let heldVideoFrameCanvas = null;
let holdVideoButton = null;
// Persistent storage keys
const STORAGE_KEYS = {
TRAPEZOID_POINTS: 'whiteboardCamera_trapezoidPoints',
WHITEBOARD_ASPECT_RATIO: 'whiteboardCamera_whiteboardAspectRatio'
};
// Variables for draggable trapezoid corners
let htmlHandles = []; // To store the DOM elements for handles
let draggedHtmlHandle = null; // The HTML handle element being dragged
const HANDLE_SIZE = 20; // Pixel dimension of the square HTML handle (matches CSS)
// Global variable to control initial phase ('setup' or 'whiteboard')
let initialPhase = 'setup';
// Maps handle index (0:BR, 1:BL, 2:UL, 3:UR) to trapezoidPoints index
const trapezoidPointIndices = [1, 0, 3, 2];
// Whiteboard resizing variables
let wbLeftHandle, wbRightHandle;
let isResizingWhiteboard = false;
let draggedWhiteboardHandleSide = null;
let currentWhiteboardDrawingWidth, currentWhiteboardDrawingHeight;
let wbResizeInitialMouseX, wbResizeInitialWidth;
// Load whiteboard aspect ratio from localStorage
function loadWhiteboardAspectRatio() {
try {
const stored = localStorage.getItem(STORAGE_KEYS.WHITEBOARD_ASPECT_RATIO);
if (stored) {
const aspectRatio = parseFloat(stored);
if (aspectRatio > 0 && aspectRatio < 10) { // Reasonable bounds
return aspectRatio;
}
}
} catch (error) {
console.warn('Error loading whiteboard aspect ratio from localStorage:', error);
}
return 1.0; // Default 1:1 aspect ratio
}
// Save whiteboard aspect ratio to localStorage
function saveWhiteboardAspectRatio() {
try {
const aspectRatio = currentWhiteboardDrawingWidth / currentWhiteboardDrawingHeight;
localStorage.setItem(STORAGE_KEYS.WHITEBOARD_ASPECT_RATIO, aspectRatio.toString());
} catch (error) {
console.warn('Error saving whiteboard aspect ratio to localStorage:', error);
}
}
// Global variable for the rotating triangle's angle
let triangleAngle = 0;
// Flipper variables
let currentSlide = 0;
let flipperInterval = null;
const FLIPPER_DURATION = 10000; // 10 seconds
// Global constants for initial trapezoid ratios, derived from the CSS #trapezoid-overlay clip-path
// These ensure the drawn trapezoid aligns with the visual guide.
// The #trapezoid-overlay has width: 80% and is centered (10% margin on each side).
// Its clip-path defines points relative to its own 80% width.
// Bottom points: 0% and 100% of its 80% width -> effectively 10% and 90% of videoWidth.
const INITIAL_BOTTOM_WIDTH_RATIO = 0.8; // (0.9 - 0.1)
// Top points: 15% and 85% of its 80% width -> effectively (0.1 + 0.15*0.8) and (0.1 + 0.85*0.8) of videoWidth
// -> 0.22 and 0.78 of videoWidth. Width = 0.78 - 0.22 = 0.56.
const INITIAL_TOP_WIDTH_RATIO = 0.56;
// The #trapezoid-overlay has height: 60% and bottom: 0. Top of div is at 40% of videoHeight.
// Its clip-path's 0% height is the top of the div, 100% height is the bottom of the div.
// So, the drawn trapezoid's bottom Y will be videoHeight, and its top Y will be 0.4 * videoHeight.
// This means the effective height is 0.6 * videoHeight.
const INITIAL_TRAPEZOID_HEIGHT_RATIO = 0.6;
// Initialize the application when the DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
// Get DOM elements
webcam = document.getElementById('webcam');
overlayCanvas = document.getElementById('overlay-canvas');
whiteboardCanvas = document.getElementById('whiteboard-canvas');
magnifierDiv = document.getElementById('magnifier');
magnifierCanvas = document.getElementById('magnifier-canvas');
holdVideoButton = document.getElementById('hold-video-btn');
overlayCtx = overlayCanvas.getContext('2d');
heldVideoFrameCanvas = document.createElement('canvas'); // Initialize, dimensions set later
if (magnifierCanvas) { // Ensure it exists before getting context
magnifierCtx = magnifierCanvas.getContext('2d');
magnifierCanvas.width = 100; // Set drawing surface size
magnifierCanvas.height = 100;
}
// whiteboardCtx is no longer initialized here, as whiteboardCanvas will be used for WebGL.
// Set up event listeners
document.getElementById('start-btn').addEventListener('click', startWhiteboardMode);
document.getElementById('back-btn').addEventListener('click', backToSetupMode);
document.getElementById('copy-btn').addEventListener('click', copyWhiteboardToClipboard);
document.getElementById('save-btn').addEventListener('click', saveWhiteboard);
document.getElementById('minus-btn').addEventListener('click', () => adjustZoom(-5));
document.getElementById('plus-btn').addEventListener('click', () => adjustZoom(5));
document.getElementById('zoom-slider').addEventListener('input', handleZoomSlider);
holdVideoButton.addEventListener('click', toggleVideoHold);
// Add event listeners for dragging trapezoid corners
// overlayCanvas.addEventListener('mousedown', handleTrapezoidInteractionStart); // Removed to prevent dragging canvas itself
document.addEventListener('mousemove', handleTrapezoidInteractionMove);
document.addEventListener('mouseup', handleTrapezoidInteractionEnd);
// Touch events for document are for moving/ending drag
document.addEventListener('touchmove', handleTrapezoidInteractionMove, { passive: false });
document.addEventListener('touchend', handleTrapezoidInteractionEnd);
// Get HTML handles
for (let i = 0; i < 4; i++) {
const handle = document.getElementById(`handle-${i}`);
htmlHandles.push(handle);
// Attach mousedown/touchstart to each handle
handle.addEventListener('mousedown', handleTrapezoidInteractionStart);
handle.addEventListener('touchstart', handleTrapezoidInteractionStart, { passive: false });
}
// Initialize webcam
initWebcam();
// Add resize listener to update handle positions and whiteboard size
window.addEventListener('resize', () => {
updateHtmlHandlesPositions(); // For setup view
if (isWhiteboardMode && whiteboardCanvas && currentWhiteboardDrawingWidth && currentWhiteboardDrawingHeight) {
// Recalculate whiteboard size based on new container dimensions
const canvasContainer = document.getElementById('canvas-container');
if (canvasContainer) {
const containerSize = Math.min(canvasContainer.offsetWidth, canvasContainer.offsetHeight);
console.log('Window resized - new container size:', containerSize);
// Update whiteboard dimensions to fill new container size
currentWhiteboardDrawingWidth = containerSize;
currentWhiteboardDrawingHeight = containerSize;
whiteboardCanvas.width = currentWhiteboardDrawingWidth;
whiteboardCanvas.height = currentWhiteboardDrawingHeight;
// Update WebGL viewport and buffers
if (gl && program) {
gl.viewport(0, 0, currentWhiteboardDrawingWidth, currentWhiteboardDrawingHeight);
gl.useProgram(program);
gl.uniform2f(resolutionLocation, currentWhiteboardDrawingWidth, currentWhiteboardDrawingHeight);
// Update position buffer with new dimensions
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
setRectangle(gl, 0, 0, currentWhiteboardDrawingWidth, currentWhiteboardDrawingHeight);
}
}
updateWhiteboardLayout(); // Update layout and handle positions
}
});
// Handle initial phase display based on the global variable
if (initialPhase === 'whiteboard') {
document.getElementById('setup-view').style.display = 'none';
document.getElementById('whiteboard-view').style.display = 'flex';
document.getElementById('whiteboard-view').style.opacity = '1';
isWhiteboardMode = true; // Set mode immediately
// updateWhiteboardLayout will be called in initWebcam after dimensions are known
} else {
document.getElementById('setup-view').classList.add('active'); // Ensure setup view is active initially
// Initialize flipper
initializeFlipper();
}
// Whiteboard resize handles
wbLeftHandle = document.getElementById('wb-left-handle');
wbRightHandle = document.getElementById('wb-right-handle');
// const canvasContainer = document.getElementById('canvas-container'); // No longer needed for these listeners
// Mouseenter/mouseleave listeners on canvasContainer for handle visibility are removed.
// Visibility is now controlled by mode (setup/whiteboard) and CSS handles hover effects.
[wbLeftHandle, wbRightHandle].forEach(handle => {
handle.addEventListener('mousedown', startWhiteboardResize);
});
document.addEventListener('mousemove', doWhiteboardResize);
document.addEventListener('mouseup', stopWhiteboardResize);
// Global keydown listener for Spacebar to toggle video hold and Enter to switch to whiteboard mode
document.addEventListener('keydown', (event) => {
if (event.code === 'Space' && !isWhiteboardMode) {
// Prevent toggling if focus is on an input or button
const activeElement = document.activeElement;
if (activeElement && (activeElement.tagName === 'INPUT' || activeElement.tagName === 'BUTTON')) {
return;
}
event.preventDefault(); // Prevent default spacebar action (e.g., scrolling or button click if focused)
toggleVideoHold();
} else if (event.code === 'Enter' && !isWhiteboardMode) {
// Prevent switching if focus is on an input or button
const activeElement = document.activeElement;
if (activeElement && (activeElement.tagName === 'INPUT' || activeElement.tagName === 'BUTTON')) {
return;
}
event.preventDefault(); // Prevent default enter action
startWhiteboardMode();
}
});
});
// Initialize webcam access
async function initWebcam(deviceId = null) {
try {
// Stop any existing stream before starting a new one
if (webcam.srcObject) {
webcam.srcObject.getTracks().forEach(track => track.stop());
}
const videoConstraints = {
width: { ideal: 1280 },
height: { ideal: 720 }
};
if (deviceId) {
videoConstraints.deviceId = { exact: deviceId };
} else {
// Only use facingMode if no specific deviceId is requested
videoConstraints.facingMode = 'environment';
}
const stream = await navigator.mediaDevices.getUserMedia({ video: videoConstraints });
webcam.srcObject = stream;
// Wait for video metadata to load
webcam.onloadedmetadata = async () => { // Made async to await populateCameraList
videoWidth = webcam.videoWidth;
videoHeight = webcam.videoHeight;
// Get camera container dimensions
const cameraContainer = document.getElementById('camera-container');
const containerWidth = cameraContainer.clientWidth;
const aspectRatio = videoWidth / videoHeight;
// Set video display dimensions
webcam.style.width = `${containerWidth}px`;
webcam.style.height = `${containerWidth / aspectRatio}px`;
// Set overlay canvas to match displayed video size
overlayCanvas.width = containerWidth;
overlayCanvas.height = containerWidth / aspectRatio;
// Update videoWidth/height variables to match displayed size
videoWidth = containerWidth;
videoHeight = containerWidth / aspectRatio;
// Set dimensions for heldVideoFrameCanvas based on actual video stream dimensions
if (heldVideoFrameCanvas) {
heldVideoFrameCanvas.width = webcam.videoWidth;
heldVideoFrameCanvas.height = webcam.videoHeight;
}
// --- Whiteboard Canvas initial drawing surface size ---
const canvasContainer = document.getElementById('canvas-container');
console.log('initWebcam container dimensions:', {
clientWidth: canvasContainer.clientWidth,
clientHeight: canvasContainer.clientHeight,
offsetWidth: canvasContainer.offsetWidth,
offsetHeight: canvasContainer.offsetHeight
});
// Load saved aspect ratio or use 1:1 default
const savedAspectRatio = loadWhiteboardAspectRatio();
console.log('Loaded aspect ratio:', savedAspectRatio);
// Height should always fill the viewport height
currentWhiteboardDrawingHeight = canvasContainer.offsetHeight;
// Width is calculated based on saved aspect ratio
currentWhiteboardDrawingWidth = currentWhiteboardDrawingHeight * savedAspectRatio;
// If width exceeds container width, constrain by width and recalculate height
if (currentWhiteboardDrawingWidth > canvasContainer.offsetWidth) {
currentWhiteboardDrawingWidth = canvasContainer.offsetWidth;
currentWhiteboardDrawingHeight = currentWhiteboardDrawingWidth / savedAspectRatio;
}
console.log('Set initial whiteboard dimensions:', {
width: currentWhiteboardDrawingWidth,
height: currentWhiteboardDrawingHeight,
aspectRatio: currentWhiteboardDrawingWidth / currentWhiteboardDrawingHeight
});
whiteboardCanvas.width = currentWhiteboardDrawingWidth;
whiteboardCanvas.height = currentWhiteboardDrawingHeight;
// Calculate trapezoid points based on video dimensions
calculateTrapezoidPoints(); // This will also call updateHtmlHandlesPositions
updatePerspectiveMatrix(); // Initial calculation of the perspective matrix
if (!isWhiteboardMode) { // If in setup mode
drawTrapezoid(); // Ensure handles are styled (visible) and trapezoid drawn correctly initially
// Ensure handles are visible immediately after initialization
htmlHandles.forEach(handle => {
if (handle) handle.style.display = 'block';
});
}
// Start drawing loop
requestAnimationFrame(drawLoop);
// If starting directly in whiteboard mode, ensure WebGL is initialized after canvas is ready
if (initialPhase === 'whiteboard' && isWhiteboardMode) {
if (!isWebGLInitialized) {
// Defer WebGL initialization with a short timeout.
setTimeout(() => {
requestAnimationFrame(() => {
initWebGL();
isWebGLInitialized = true;
// Recompute perspective matrix after initial whiteboard setup
updatePerspectiveMatrix();
updateWhiteboardLayout(); // Position and style canvas and handles
});
}, 100);
} else {
// If WebGL already initialized (e.g., camera change while in whiteboard initialPhase)
// Recompute perspective matrix after aspect ratio changes
updatePerspectiveMatrix();
updateWhiteboardLayout(); // Ensure layout and handles are updated
}
}
};
} catch (error) {
console.error('Error accessing webcam:', error);
alert('Unable to access webcam. Please ensure you have granted camera permissions.');
}
}
// Global flag to ensure WebGL is initialized only once
let isWebGLInitialized = false;
// Global flag to ensure perspective info is logged only once
let hasLoggedPerspectiveInfo = false;
// Load trapezoid points from localStorage
function loadTrapezoidPoints() {
try {
const stored = localStorage.getItem(STORAGE_KEYS.TRAPEZOID_POINTS);
if (stored) {
const parsed = JSON.parse(stored);
// Validate that we have 4 points with 2 coordinates each
if (Array.isArray(parsed) && parsed.length === 4 &&
parsed.every(point => Array.isArray(point) && point.length === 2)) {
return parsed;
}
}
} catch (error) {
console.warn('Error loading trapezoid points from localStorage:', error);
}
return null;
}
// Save trapezoid points to localStorage
function saveTrapezoidPoints() {
try {
// Convert from display coordinates to camera coordinates before saving
const cameraCoordinates = trapezoidPoints.map(point => [
(point[0] / videoWidth) * webcam.videoWidth,
(point[1] / videoHeight) * webcam.videoHeight
]);
localStorage.setItem(STORAGE_KEYS.TRAPEZOID_POINTS, JSON.stringify(cameraCoordinates));
} catch (error) {
console.warn('Error saving trapezoid points to localStorage:', error);
}
}
// Calculate trapezoid points based on video dimensions and zoom factor
function calculateTrapezoidPoints(zoomFactor = 1.0) {
const width = videoWidth;
const height = videoHeight;
// Try to load saved trapezoid points first
const savedPoints = loadTrapezoidPoints();
if (savedPoints && zoomFactor === 1.0) {
// Convert from camera coordinates to display coordinates
trapezoidPoints = savedPoints.map(point => [
(point[0] / webcam.videoWidth) * videoWidth,
(point[1] / webcam.videoHeight) * videoHeight
]);
// Update the perspective matrix whenever trapezoid points change
updatePerspectiveMatrix();
// Update HTML handle positions
updateHtmlHandlesPositions();
return;
}
// Fallback to default calculation
// Anchor the bottom of the trapezoid to the bottom of the canvas
const bottomY = height;
// Calculate current dimensions based on initial ratios and zoom factor
const currentTrapezoidHeight = INITIAL_TRAPEZOID_HEIGHT_RATIO * height * zoomFactor;
const currentBottomWidth = INITIAL_BOTTOM_WIDTH_RATIO * width * zoomFactor;
const currentTopWidth = INITIAL_TOP_WIDTH_RATIO * width * zoomFactor;
// Ensure trapezoid doesn't go out of bounds (top Y should not be negative)
const topY = Math.max(0, bottomY - currentTrapezoidHeight);
// Calculate horizontal positions, centered
const bottomLeftX = (width - currentBottomWidth) / 2;
const bottomRightX = (width + currentBottomWidth) / 2;
const topLeftX = (width - currentTopWidth) / 2;
const topRightX = (width + currentTopWidth) / 2;
// Define trapezoid points (clockwise from bottom-left)
trapezoidPoints = [
[bottomLeftX, bottomY], // Bottom-left
[bottomRightX, bottomY], // Bottom-right
[topRightX, topY], // Top-right
[topLeftX, topY] // Top-left
];
// Update the perspective matrix whenever trapezoid points change
updatePerspectiveMatrix();
// Update HTML handle positions
updateHtmlHandlesPositions();
}
// Update positions of HTML handles based on trapezoidPoints
function updateHtmlHandlesPositions() {
if (!videoWidth || !videoHeight || htmlHandles.length === 0) return;
console.log('updateHtmlHandlesPositions running, timestamp:', Date.now()); // DEBUG LOG
const cameraContainer = document.getElementById('camera-container');
if (!cameraContainer) return;
const containerRect = cameraContainer.getBoundingClientRect();
for (let i = 0; i < htmlHandles.length; i++) { // Iterate through handles
const handleEl = htmlHandles[i];
const actualTrapezoidPointIndex = trapezoidPointIndices[i];
const canvasP = trapezoidPoints[actualTrapezoidPointIndex];
if (handleEl && canvasP) {
// Convert canvas coordinates to CSS pixel values relative to the container
// This will be the target center for our handle's circle.
let targetCenterX = (canvasP[0] / videoWidth) * containerRect.width;
let targetCenterY = (canvasP[1] / videoHeight) * containerRect.height;
// Apply adjustments to the target center position.
// These adjustments were originally for the needle tip, but we'll keep them
// to ensure the circle center aligns where the tip was intended.
// i is the htmlHandles index:
// 0: Visual Bottom-Right handle, "UL" label
// 1: Visual Bottom-Left handle, "UR" label
// 2: Visual Top-Left handle, "BR" label
// 3: Visual Top-Right handle, "BL" label
if (i === 0) { // Visual Bottom-Right ("UL")
targetCenterX -= 2;
} else if (i === 1) { // Visual Bottom-Left ("UR")
targetCenterX += 2;
} else if (i === 2) { // Visual Top-Left ("BR")
targetCenterX -= 4;
} else if (i === 3) { // Visual Top-Right ("BL")
targetCenterX += 4;
}
// Position the handle element so its center aligns with (targetCenterX, targetCenterY).
// The draggable-handle is 16x16px. Its center is at (8px, 8px) from its top-left.
handleEl.style.left = `${targetCenterX - 8}px`;
handleEl.style.top = `${targetCenterY - 8}px`;
// The circle element is positioned at (2px, 2px) within the draggable-handle.
// Its CSS width/height is 12px. With a 2px border, its visual size is 16px.
// So it visually fills the draggable-handle. No specific JS positioning needed for it here.
const circleEl = handleEl.querySelector('.handle-circle');
if (circleEl) {
// Ensure default position if it was ever changed by mistake
circleEl.style.left = '2px';
circleEl.style.top = '2px';
}
// Position the label based on handle type (relative to the handleEl, which is now centered on the point)
const labelEl = handleEl.querySelector('.corner-label');
if (labelEl) {
// Position labels based on visual handle index (i), considering the diagonal swap.
// htmlHandles[0] (Visually BR, effectively UL)
if (i === 0) {
labelEl.style.left = '0px'; // Centered above (like original UL/UR)
labelEl.style.top = '-25px';
labelEl.style.transform = 'translateX(-50%)';
// htmlHandles[1] (Visually BL, effectively UR)
} else if (i === 1) {
labelEl.style.left = '0px'; // Centered above (like original UL/UR)
labelEl.style.top = '-25px';
labelEl.style.transform = 'translateX(-50%)';
// htmlHandles[2] (Visually UL, effectively BR)
} else if (i === 2) {
labelEl.style.left = '-25px'; // Left and up (like original BR)
labelEl.style.top = '-20px';
labelEl.style.transform = ''; // Clear transform if not needed
// htmlHandles[3] (Visually UR, effectively BL)
} else if (i === 3) {
labelEl.style.left = '20px'; // Right and up (like original BL)
labelEl.style.top = '-20px';
labelEl.style.transform = ''; // Clear transform if not needed
}
}
}
}
}
// Recalculate and update the perspective matrix
function updatePerspectiveMatrix() {
if (videoWidth && videoHeight && trapezoidPoints && trapezoidPoints.length === 4) {
hasLoggedPerspectiveInfo = false; // Reset log flag so it logs for the new matrix
const transformData = calculatePerspectiveMatrix();
if (transformData && transformData.matrix) {
currentPerspectiveMatrix = transformData.matrix;
currentSrcPoints = transformData.srcPoints; // Store srcPoints for logging
} else {
console.error("Failed to calculate perspective matrix. Using identity matrix.");
currentPerspectiveMatrix = [1,0,0, 0,1,0, 0,0,1]; // Fallback to identity
// Attempt to use original trapezoid points if available, otherwise empty
currentSrcPoints = trapezoidPoints ? trapezoidPoints.map(point => [point[0] / videoWidth, point[1] / videoHeight]) : [];
}
} else {
// Not enough data to calculate, set to identity (no transformation)
currentPerspectiveMatrix = [1,0,0, 0,1,0, 0,0,1];
currentSrcPoints = []; // Default to empty array
console.warn("Not enough data for perspective matrix, using identity.");
}
}
// Main drawing loop
function drawLoop() {
if (!isWhiteboardMode) {
overlayCtx.clearRect(0, 0, overlayCanvas.width, overlayCanvas.height);
if (isVideoHoldActive && heldVideoFrameCanvas && heldVideoFrameCanvas.width > 0) {
// Draw the held frame onto the overlay canvas, scaled to fit.
overlayCtx.drawImage(heldVideoFrameCanvas, 0, 0, heldVideoFrameCanvas.width, heldVideoFrameCanvas.height, 0, 0, overlayCanvas.width, overlayCanvas.height);
} else if (webcam && webcam.readyState >= webcam.HAVE_CURRENT_DATA) {
// If not holding, draw the live video frame onto the overlay canvas.
overlayCtx.drawImage(webcam, 0, 0, webcam.videoWidth, webcam.videoHeight, 0, 0, overlayCanvas.width, overlayCanvas.height);
}
// If webcam is not ready and not holding, overlayCanvas will be clear before drawing trapezoid.
// Draw trapezoid outline on top of the drawn video frame (or clear background)
drawTrapezoid();
} else {
// Process video frame with perspective correction
processVideoFrame();
}
// Continue the loop
requestAnimationFrame(drawLoop);
}
// Draw trapezoid outline on overlay canvas
function drawTrapezoid() {
// Draw dashed red trapezoid outline
overlayCtx.beginPath();
overlayCtx.moveTo(trapezoidPoints[0][0], trapezoidPoints[0][1]);
for (let i = 1; i < trapezoidPoints.length; i++) {
overlayCtx.lineTo(trapezoidPoints[i][0], trapezoidPoints[i][1]);
}
overlayCtx.closePath();
overlayCtx.strokeStyle = 'red';
overlayCtx.lineWidth = 2; // Adjust line width as needed
overlayCtx.setLineDash([5, 5]); // 5px dashes, 5px gaps
overlayCtx.stroke();
overlayCtx.setLineDash([]); // Reset line dash for other drawings
// Ensure HTML handles are always visible in setup mode
if (!isWhiteboardMode) {
htmlHandles.forEach(handle => {
if (handle) handle.style.display = 'block';
});
} else {
htmlHandles.forEach(handle => {
if (handle) handle.style.display = 'none';
});
}
}
// Helper function to clip a line to a rectangle using Cohen-Sutherland algorithm
function clipLineToRect(x1, y1, x2, y2, rectX, rectY, rectWidth, rectHeight) {
const INSIDE = 0; // 0000
const LEFT = 1; // 0001
const RIGHT = 2; // 0010
const BOTTOM = 4; // 0100
const TOP = 8; // 1000
function computeOutCode(x, y) {
let code = INSIDE;
if (x < rectX) code |= LEFT;
else if (x > rectX + rectWidth) code |= RIGHT;
if (y < rectY) code |= BOTTOM;
else if (y > rectY + rectHeight) code |= TOP;
return code;
}
let outcode1 = computeOutCode(x1, y1);
let outcode2 = computeOutCode(x2, y2);
let accept = false;
while (true) {
if (!(outcode1 | outcode2)) {
// Both points inside rectangle
accept = true;
break;
} else if (outcode1 & outcode2) {
// Both points share an outside zone (completely outside)
break;
} else {
// Line needs clipping
let x, y;
let outcodeOut = outcode1 ? outcode1 : outcode2;
if (outcodeOut & TOP) {
x = x1 + (x2 - x1) * (rectY + rectHeight - y1) / (y2 - y1);
y = rectY + rectHeight;
} else if (outcodeOut & BOTTOM) {
x = x1 + (x2 - x1) * (rectY - y1) / (y2 - y1);
y = rectY;
} else if (outcodeOut & RIGHT) {
y = y1 + (y2 - y1) * (rectX + rectWidth - x1) / (x2 - x1);
x = rectX + rectWidth;
} else if (outcodeOut & LEFT) {
y = y1 + (y2 - y1) * (rectX - x1) / (x2 - x1);
x = rectX;
}
if (outcodeOut === outcode1) {
x1 = x;
y1 = y;
outcode1 = computeOutCode(x1, y1);
} else {
x2 = x;
y2 = y;
outcode2 = computeOutCode(x2, y2);
}
}
}
return accept ? { x1, y1, x2, y2 } : null;
}
// Helper function to get event coordinates relative to the canvas
// This function is kept as it might be useful for other interactions with overlayCanvas,
// but it's not used for the HTML handle dragging.
function getCanvasCoordinates(event, canvas) {
const rect = canvas.getBoundingClientRect();
let clientX, clientY;
if (event.touches && event.touches.length > 0) {
clientX = event.touches[0].clientX;
clientY = event.touches[0].clientY;
} else if (event.changedTouches && event.changedTouches.length > 0) { // For touchend
clientX = event.changedTouches[0].clientX;
clientY = event.changedTouches[0].clientY;
}
else {
clientX = event.clientX;
clientY = event.clientY;
}
const scaleX = canvas.width / rect.width;
const scaleY = canvas.height / rect.height;
return {
x: (clientX - rect.left) * scaleX,
y: (clientY - rect.top) * scaleY
};
}
// Event handlers for trapezoid corner dragging (now with HTML elements)
function handleTrapezoidInteractionStart(event) {
if (isWhiteboardMode) return; // Interaction only in setup mode
// 'this' refers to the HTML handle element the event was triggered on
draggedHtmlHandle = this;
// Add grabbing cursor style to body to indicate drag, and prevent text selection
document.body.style.cursor = 'grabbing';
document.body.style.userSelect = 'none';
if (event.type === 'touchstart') {
event.preventDefault(); // Prevent scrolling/zooming
}
if (magnifierDiv) {
magnifierDiv.style.display = 'block';
}
// Initial draw of magnifier content will happen in the first move event
}
function handleTrapezoidInteractionMove(event) {
if (!draggedHtmlHandle || isWhiteboardMode) return;
if (event.type === 'touchmove' || event.type === 'mousemove') {
event.preventDefault(); // Prevent scrolling/zooming during drag
}
const cameraContainer = document.getElementById('camera-container');
if (!cameraContainer) return;
const containerRect = cameraContainer.getBoundingClientRect();
// Determine clientX/Y from touch or mouse event
const clientX = event.touches ? event.touches[0].clientX : event.clientX;
const clientY = event.touches ? event.touches[0].clientY : event.clientY;
// Calculate coordinates relative to the camera container
let containerX = clientX - containerRect.left;
let containerY = clientY - containerRect.top;
// Find the index of the dragged handle (0 for BR, 1 for BL, etc.)
const handleIdx = htmlHandles.indexOf(draggedHtmlHandle);
if (handleIdx === -1) return; // Should not happen
// Determine the actual index in trapezoidPoints array to update
const actualTrapezoidPointIndex = trapezoidPointIndices[handleIdx];
// Convert container coordinates to canvas coordinates for trapezoid points (simple scaling)
const canvasX = (containerX / containerRect.width) * videoWidth;
const canvasY = (containerY / containerRect.height) * videoHeight;
// Update the corresponding trapezoidPoint. No clamping.
trapezoidPoints[actualTrapezoidPointIndex][0] = canvasX;
trapezoidPoints[actualTrapezoidPointIndex][1] = canvasY;
// Save trapezoid points to localStorage
saveTrapezoidPoints();
// Convert container coordinates to actual video coordinates for magnifier
const videoElement = webcam;
const videoDisplayX = (containerX / containerRect.width) * videoElement.offsetWidth;
const videoDisplayY = (containerY / containerRect.height) * videoElement.offsetHeight;
const magnifierVideoX = (videoDisplayX / videoElement.offsetWidth) * videoElement.videoWidth;
const magnifierVideoY = (videoDisplayY / videoElement.offsetHeight) * videoElement.videoHeight;
// Update matrix and handle positions
updatePerspectiveMatrix();
updateHtmlHandlesPositions(); // This updates the draggedHtmlHandle's style.left/top
// Update Magnifier
const videoSourceForMagnifier = (isVideoHoldActive && heldVideoFrameCanvas && heldVideoFrameCanvas.width > 0) ? heldVideoFrameCanvas : webcam;
const magnifierReady = magnifierDiv && magnifierCtx && draggedHtmlHandle &&
( (isVideoHoldActive && heldVideoFrameCanvas && heldVideoFrameCanvas.width > 0) ||
(!isVideoHoldActive && webcam.readyState >= webcam.HAVE_CURRENT_DATA) );
if (magnifierReady) {
// Position the magnifier div near the cursor
const magnifierWidth = 100;
const magnifierHeight = 100;
// Position magnifier above the cursor with a 20px gap
magnifierDiv.style.left = `${containerX - (magnifierWidth / 2)}px`;
magnifierDiv.style.top = `${containerY - magnifierHeight - 20}px`;
// Check if cursor is within video bounds using magnifier coordinates
if (magnifierVideoX >= 0 && magnifierVideoX <= webcam.videoWidth && magnifierVideoY >= 0 && magnifierVideoY <= webcam.videoHeight) {
// Draw magnified content from the cursor position in video coordinates
const videoFeedX = magnifierVideoX; // Cursor position in video coordinates
const videoFeedY = magnifierVideoY; // Cursor position in video coordinates
const sourceSize = 50; // 50x50 pixels from video
const destSize = 100; // Drawn as 100x100 on magnifier canvas
const sx = videoFeedX - sourceSize / 2;
const sy = videoFeedY - sourceSize / 2;
magnifierCtx.clearRect(0, 0, destSize, destSize);
magnifierCtx.drawImage(videoSourceForMagnifier,
sx, sy, sourceSize, sourceSize,
0, 0, destSize, destSize);
// Draw lines from center to trapezoid corners
magnifierCtx.strokeStyle = 'rgba(255, 0, 0, 0.7)';
magnifierCtx.lineWidth = 1;
magnifierCtx.fillStyle = 'red';
// Get the trapezoid point index that corresponds to the dragged handle
const draggedTrapezoidIndex = trapezoidPointIndices[handleIdx];
// Calculate the two neighboring corner indices (previous and next in the trapezoid)
const prevIndex = (draggedTrapezoidIndex + 3) % 4; // Previous corner (wrapping around)
const nextIndex = (draggedTrapezoidIndex + 1) % 4; // Next corner (wrapping around)
// Get the current dragged corner position from the actual trapezoid point being updated
const actualTrapezoidPointIndex = trapezoidPointIndices[handleIdx];
const currentCornerX = trapezoidPoints[actualTrapezoidPointIndex][0];
const currentCornerY = trapezoidPoints[actualTrapezoidPointIndex][1];
// Convert neighbor corners to magnifier coordinates relative to current corner
const prevCornerVideoX = trapezoidPoints[prevIndex][0];
const prevCornerVideoY = trapezoidPoints[prevIndex][1];
const nextCornerVideoX = trapezoidPoints[nextIndex][0];
const nextCornerVideoY = trapezoidPoints[nextIndex][1];
// Calculate relative positions in video coordinates
const prevRelativeX = prevCornerVideoX - currentCornerX;
const prevRelativeY = prevCornerVideoY - currentCornerY;
const nextRelativeX = nextCornerVideoX - currentCornerX;
const nextRelativeY = nextCornerVideoY - currentCornerY;
// Convert to magnifier coordinates (magnification factor = destSize/sourceSize = 100/50 = 2)
const magnificationFactor = destSize / sourceSize;
const centerX = destSize / 2;
const centerY = destSize / 2;
const prevMagnifierX = centerX + (prevRelativeX * magnificationFactor);
const prevMagnifierY = centerY + (prevRelativeY * magnificationFactor);
const nextMagnifierX = centerX + (nextRelativeX * magnificationFactor);
const nextMagnifierY = centerY + (nextRelativeY * magnificationFactor);
// Debug log: print coordinates in one line
console.log(`Mouse: canvas(${containerX.toFixed(1)},${containerY.toFixed(1)}) webcam(${magnifierVideoX.toFixed(1)},${magnifierVideoY.toFixed(1)}) | Minimap: canvas(${(sx + sourceSize/2).toFixed(1)},${(sy + sourceSize/2).toFixed(1)}) webcam(${videoFeedX.toFixed(1)},${videoFeedY.toFixed(1)}) | Canvas max: (${webcam.videoWidth},${webcam.videoHeight}) | Node: y=${currentCornerY.toFixed(1)} Ymag=${centerY.toFixed(1)} | Prev: y=${prevCornerVideoY.toFixed(1)} Ymag=${prevMagnifierY.toFixed(1)} | Next: y=${nextCornerVideoY.toFixed(1)} Ymag=${nextMagnifierY.toFixed(1)}`);
magnifierCtx.beginPath();
// Draw line to previous neighbor
const clippedLine1 = clipLineToRect(centerX, centerY,
prevMagnifierX, prevMagnifierY,
0, 0, destSize, destSize);
if (clippedLine1) {
magnifierCtx.moveTo(clippedLine1.x1, clippedLine1.y1);
magnifierCtx.lineTo(clippedLine1.x2, clippedLine1.y2);
}
// Draw line to next neighbor
const clippedLine2 = clipLineToRect(centerX, centerY,
nextMagnifierX, nextMagnifierY,
0, 0, destSize, destSize);
if (clippedLine2) {
magnifierCtx.moveTo(clippedLine2.x1, clippedLine2.y1);
magnifierCtx.lineTo(clippedLine2.x2, clippedLine2.y2);
}
magnifierCtx.stroke();
// Draw dots for neighbor corners if they are visible in magnifier
if (prevMagnifierX >= 0 && prevMagnifierX <= destSize &&
prevMagnifierY >= 0 && prevMagnifierY <= destSize) {
magnifierCtx.beginPath();
magnifierCtx.arc(prevMagnifierX, prevMagnifierY, 2, 0, 2 * Math.PI);
magnifierCtx.fill();
}
if (nextMagnifierX >= 0 && nextMagnifierX <= destSize &&
nextMagnifierY >= 0 && nextMagnifierY <= destSize) {
magnifierCtx.beginPath();
magnifierCtx.arc(nextMagnifierX, nextMagnifierY, 2, 0, 2 * Math.PI);
magnifierCtx.fill();
}
// Draw center dot
magnifierCtx.beginPath();
magnifierCtx.arc(destSize / 2, destSize / 2, 2, 0, 2 * Math.PI);
magnifierCtx.fill();
} else {
// Clear magnifier when outside video bounds
console.log(`Mouse: canvas(${containerX.toFixed(1)},${containerY.toFixed(1)}) webcam(${magnifierVideoX.toFixed(1)},${magnifierVideoY.toFixed(1)}) | OUT OF BOUNDS | Canvas max: (${webcam.videoWidth},${webcam.videoHeight})`);
magnifierCtx.clearRect(0, 0, destSize, destSize);
// Fill with a dark background to indicate out of bounds
magnifierCtx.fillStyle = 'rgba(0, 0, 0, 0.8)';
magnifierCtx.fillRect(0, 0, destSize, destSize);
// Draw center dot even when out of bounds
const destSize = 100; // Define destSize for out-of-bounds case
magnifierCtx.fillStyle = 'red';
magnifierCtx.beginPath();
magnifierCtx.arc(destSize / 2, destSize / 2, 2, 0, 2 * Math.PI);
magnifierCtx.fill();
}
}
}
function handleTrapezoidInteractionEnd(event) {
if (!draggedHtmlHandle) return;
draggedHtmlHandle = null;
// Restore cursor and text selection
document.body.style.cursor = 'default';
document.body.style.userSelect = 'auto';
if (magnifierDiv) {
magnifierDiv.style.display = 'none';
}
}
// Initialize WebGL for perspective correction
function initWebGL() {
console.log('=== INITIALIZING WEBGL ===');
console.log('whiteboardCanvas element:', whiteboardCanvas);
console.log('Canvas dimensions:', whiteboardCanvas?.width, 'x', whiteboardCanvas?.height);
console.log('Canvas style dimensions:', whiteboardCanvas?.style.width, 'x', whiteboardCanvas?.style.height);
if (!whiteboardCanvas) {
console.error('whiteboardCanvas element is not found or not ready.');
alert('Critical error: Whiteboard canvas element not found.');
return;
}
// Get WebGL context
gl = whiteboardCanvas.getContext('webgl', { preserveDrawingBuffer: true }) ||
whiteboardCanvas.getContext('experimental-webgl', { preserveDrawingBuffer: true });
if (!gl) {
console.error('WebGL not supported. getContext() returned null.');
alert('Your browser does not support WebGL, which is required for this application.');
return;
}
console.log('WebGL context obtained successfully!');
console.log('WebGL version:', gl.getParameter(gl.VERSION));
console.log('WebGL vendor:', gl.getParameter(gl.VENDOR));
console.log('WebGL renderer:', gl.getParameter(gl.RENDERER));
// Get shader sources
const vertexShaderSource = document.getElementById('vertex-shader').text;
const fragmentShaderSource = document.getElementById('fragment-shader').text;
// Create shader program
console.log('Creating shaders...');
const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource);
const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource);
if (!vertexShader || !fragmentShader) {
console.error('Failed to create shaders');
return;
}
program = createProgram(gl, vertexShader, fragmentShader);
if (!program) {
console.error('Failed to create shader program');
return;
}
console.log('Shader program created successfully');
// Look up attribute locations
positionLocation = gl.getAttribLocation(program, 'a_position');
texCoordLocation = gl.getAttribLocation(program, 'a_texCoord');
// Look up uniform locations
resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
matrixLocation = gl.getUniformLocation(program, 'u_matrix');
console.log('Attribute/Uniform locations:');
console.log(' positionLocation:', positionLocation);
console.log(' texCoordLocation:', texCoordLocation);
console.log(' resolutionLocation:', resolutionLocation);
console.log(' matrixLocation:', matrixLocation);
// Create buffers
positionBuffer = gl.createBuffer(); // Use global variable
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
// Use whiteboardCanvas dimensions for the rectangle, which should match videoWidth/Height
setRectangle(gl, 0, 0, whiteboardCanvas.width, whiteboardCanvas.height);
// Enable and point position attribute
gl.enableVertexAttribArray(positionLocation);
gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
texCoordBuffer = gl.createBuffer(); // Use global variable
gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
0.0, 0.0,
1.0, 0.0,
0.0, 1.0,
0.0, 1.0,
1.0, 0.0,
1.0, 1.0
]), gl.STATIC_DRAW);
// Enable and point texCoord attribute
gl.enableVertexAttribArray(texCoordLocation);
gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);
// Create texture
const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
// Set texture parameters