-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscripts.js
More file actions
977 lines (832 loc) · 39.7 KB
/
scripts.js
File metadata and controls
977 lines (832 loc) · 39.7 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
class ASCIICamera {
constructor() {
// DOM Elements
this.video = document.getElementById('video');
this.cameraSelect = document.getElementById('cameraSelect');
this.asciiOutput = document.getElementById('asciiOutput');
this.startButton = document.getElementById('startCamera');
this.stopButton = document.getElementById('stopCamera');
this.resolutionSelect = document.getElementById('resolution');
this.asciiStyleSelect = document.getElementById('asciiStyle');
this.toggleVideoButton = document.getElementById('toggleVideo');
this.captureFrameButton = document.getElementById('captureFrame');
this.saveImageButton = document.getElementById('saveImage');
this.printButton = document.getElementById('printAscii');
this.copyButton = document.getElementById('copyClipboard');
this.refreshCamerasButton = document.getElementById('refreshCameras');
// Modal elements
this.captureModal = document.getElementById('captureModal');
this.capturedAscii = document.getElementById('capturedAscii');
this.saveCaptureButton = document.getElementById('saveCapture');
this.copyCaptureButton = document.getElementById('copyCapture');
this.printCaptureButton = document.getElementById('printCapture');
this.downloadTextButton = document.getElementById('downloadText');
this.closeModalButton = document.getElementById('closeModal');
// Info elements
this.status = document.getElementById('status');
this.videoResolution = document.getElementById('videoResolution');
this.asciiResolution = document.getElementById('asciiResolution');
this.frameRate = document.getElementById('frameRate');
this.asciiSize = document.getElementById('asciiSize');
this.lastCapture = document.getElementById('lastCapture');
// Variables
this.stream = null;
this.availableCameras = [];
this.selectedCameraId = null;
this.canvas = document.createElement('canvas');
this.ctx = this.canvas.getContext('2d', { willReadFrequently: true });
this.animationId = null;
this.lastFrameTime = 0;
this.frameCount = 0;
this.fps = 0;
this.showVideo = true;
this.isProcessing = false;
this.capturedAsciiText = null;
this.currentAsciiText = null;
// ASCII Character Sets
this.asciiChars = {
simple: '@%#*+=-:. ',
detailed: '$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,"^`\'. ',
blocks: '█▓▒░ ',
inverse: ' .:-=+*#%@',
binary: '01',
};
// Resolution presets - Adjusted for 16:9 aspect ratio and character aspect ratio
// ASCII characters are roughly 2:1 (height:width), so we adjust target dimensions
this.resolutions = {
'ultra-low': { width: 40, height: 22 }, // 16:9 adjusted for character aspect
'low': { width: 60, height: 34 },
'medium': { width: 100, height: 56 },
'high': { width: 140, height: 79 },
'ultra': { width: 180, height: 101 },
'native': { width: 0, height: 0 } // Will be calculated
};
this.aspectRatio = 16 / 9; // Default 16:9
this.characterAspectRatio = 2.0; // ASCII characters are about 2x taller than wide
this.bindEvents();
this.updateDisplayInfo();
this.requestMinimalPermission();
}
bindEvents() {
this.cameraSelect.addEventListener('change', () => this.onCameraChange());
this.startButton.addEventListener('click', () => this.startCamera());
this.stopButton.addEventListener('click', () => this.stopCamera());
this.resolutionSelect.addEventListener('change', () => this.updateResolution());
this.asciiStyleSelect.addEventListener('change', () => this.updateAsciiStyle());
this.toggleVideoButton.addEventListener('click', () => this.toggleVideo());
this.captureFrameButton.addEventListener('click', () => this.captureFrame());
this.saveImageButton.addEventListener('click', () => this.saveAsImage());
this.printButton.addEventListener('click', () => this.printAscii());
this.copyButton.addEventListener('click', () => this.copyToClipboard());
// Modal events
this.refreshCamerasButton.addEventListener('click', () => this.refreshCameras());
this.saveCaptureButton.addEventListener('click', () => this.saveCaptureAsImage());
this.copyCaptureButton.addEventListener('click', () => this.copyCaptureToClipboard());
this.printCaptureButton.addEventListener('click', () => this.printCapture());
this.downloadTextButton.addEventListener('click', () => this.downloadAsText());
this.closeModalButton.addEventListener('click', () => this.closeModal());
// Close modal when clicking outside
this.captureModal.addEventListener('click', (e) => {
if (e.target === this.captureModal) {
this.closeModal();
}
});
// Handle keyboard shortcuts
document.addEventListener('keydown', (e) => {
if (e.ctrlKey && e.key === 's') {
e.preventDefault();
this.captureFrame();
}
if (e.key === 'Escape') {
this.closeModal();
}
});
}
async requestMinimalPermission() {
try {
// First, check if we already have permission by trying to enumerate devices
// without requesting camera access first
await this.enumerateCameras();
// If we got camera names (not just generic names), we already have permission
const hasPermission = this.availableCameras.some(camera =>
camera.label && !camera.label.startsWith('Camera ')
);
if (hasPermission) {
console.log('Already have camera permission');
return;
}
// We don't have permission yet. Try to get minimal permission
// by requesting access to a very low-resolution camera
this.status.textContent = 'Requesting camera access...';
this.status.className = 'status-indicator loading';
// Try to get permission with minimal constraints
const tempStream = await navigator.mediaDevices.getUserMedia({
video: {
width: { ideal: 1 }, // Minimal resolution
height: { ideal: 1 }, // Minimal resolution
frameRate: { ideal: 1 } // Minimal framerate
},
audio: false
});
// Immediately stop the stream (we just needed permission)
tempStream.getTracks().forEach(track => {
track.stop();
});
// Now enumerate cameras again - this time we should get proper labels
await this.enumerateCameras();
this.status.textContent = 'Ready';
this.status.className = 'status-indicator';
// If we have cameras, auto-select the first one
if (this.availableCameras.length > 0 && !this.selectedCameraId) {
this.cameraSelect.value = this.availableCameras[0].deviceId;
this.selectedCameraId = this.availableCameras[0].deviceId;
}
} catch (error) {
console.log('Minimal permission request failed or user denied:', error);
// User denied permission or error occurred
// Still try to enumerate cameras (will show generic names)
await this.enumerateCameras();
this.status.textContent = 'Click "Start Camera" to begin';
this.status.className = 'status-indicator';
// Update camera select to indicate permission needed
if (this.availableCameras.length === 0) {
const option = document.createElement('option');
option.value = '';
option.textContent = '⚠️ Camera access required';
this.cameraSelect.appendChild(option);
}
}
}
async enumerateCameras() {
try {
const devices = await navigator.mediaDevices.enumerateDevices();
this.availableCameras = devices.filter(device => device.kind === 'videoinput');
// Clear existing options except the first one
while (this.cameraSelect.options.length > 1) {
this.cameraSelect.remove(1);
}
// If no cameras found
if (this.availableCameras.length === 0) {
const option = document.createElement('option');
option.value = '';
option.textContent = 'No cameras detected';
this.cameraSelect.appendChild(option);
return this.availableCameras;
}
// Check if we have proper labels (indicates we have permission)
const hasDetailedLabels = this.availableCameras.some(camera =>
camera.label && !camera.label.startsWith('Camera ')
);
// Add camera options
this.availableCameras.forEach((camera, index) => {
const option = document.createElement('option');
option.value = camera.deviceId;
let label = camera.label || `Camera ${index + 1}`;
// Check if we have permission (detailed labels)
if (!hasDetailedLabels && camera.label && camera.label.startsWith('Camera ')) {
// We don't have full permission yet
label = `🔒 ${label} (permission needed)`;
} else {
// We have permission, show detailed info
if (camera.label) {
if (camera.label.toLowerCase().includes('back') ||
camera.label.toLowerCase().includes('rear')) {
label = '📷 Back Camera';
} else if (camera.label.toLowerCase().includes('front')) {
label = '📱 Front Camera';
} else if (camera.label.toLowerCase().includes('external')) {
label = '🔌 External Camera';
} else if (camera.label.toLowerCase().includes('virtual')) {
label = '🖥️ Virtual Camera';
} else {
label = `📹 ${label}`;
}
} else {
label = `📹 Camera ${index + 1}`;
}
}
option.textContent = label;
option.title = camera.label || `Camera device ${index + 1}`;
this.cameraSelect.appendChild(option);
});
// Auto-select logic
if (this.selectedCameraId) {
// Keep current selection if it exists
if (!this.availableCameras.some(cam => cam.deviceId === this.selectedCameraId)) {
this.selectedCameraId = null;
this.cameraSelect.value = '';
}
} else if (this.availableCameras.length > 0) {
// Try to auto-select back camera first, then front, then any
const backCamera = this.availableCameras.find(cam =>
cam.label && (cam.label.toLowerCase().includes('back') ||
cam.label.toLowerCase().includes('rear'))
);
const frontCamera = this.availableCameras.find(cam =>
cam.label && cam.label.toLowerCase().includes('front')
);
if (backCamera) {
this.selectedCameraId = backCamera.deviceId;
this.cameraSelect.value = backCamera.deviceId;
} else if (frontCamera) {
this.selectedCameraId = frontCamera.deviceId;
this.cameraSelect.value = frontCamera.deviceId;
} else {
this.selectedCameraId = this.availableCameras[0].deviceId;
this.cameraSelect.value = this.availableCameras[0].deviceId;
}
}
return this.availableCameras;
} catch (error) {
console.error('Error enumerating cameras:', error);
// Show error in dropdown
while (this.cameraSelect.options.length > 1) {
this.cameraSelect.remove(1);
}
const option = document.createElement('option');
option.value = '';
option.textContent = '❌ Error detecting cameras';
this.cameraSelect.appendChild(option);
return [];
}
}
onCameraChange() {
this.selectedCameraId = this.cameraSelect.value;
// If camera is running, restart it with the new selection
if (this.stream) {
this.stopCamera();
setTimeout(() => {
this.startCamera();
}, 100);
}
}
async refreshCameras() {
this.showAlert('Refreshing camera list...', 'info');
await this.enumerateCameras();
this.showAlert('Camera list updated!', 'success');
}
async startCamera() {
try {
this.status.textContent = 'Requesting camera access...';
this.status.className = 'status-indicator loading';
// First, enumerate cameras if we haven't already
if (this.availableCameras.length === 0) {
await this.enumerateCameras();
}
// Check if we need to update labels after getting permission
const needsPermissionUpdate = this.availableCameras.some(camera =>
camera.label && camera.label.startsWith('Camera ')
);
// Build constraints
const constraints = {
video: {
width: { ideal: 1920 },
height: { ideal: 1080 },
aspectRatio: 16/9
}
};
// If a specific camera is selected, use it
if (this.selectedCameraId) {
constraints.video.deviceId = { exact: this.selectedCameraId };
} else {
// No camera selected, try to get environment camera
constraints.video.facingMode = 'environment';
}
this.stream = await navigator.mediaDevices.getUserMedia(constraints);
this.video.srcObject = this.stream;
await new Promise((resolve) => {
this.video.onloadedmetadata = () => {
this.video.play().then(resolve);
};
});
// After getting permission, update camera list with proper labels
if (needsPermissionUpdate) {
await this.enumerateCameras();
}
// Update UI for active camera
if (this.selectedCameraId) {
const selectedCamera = this.availableCameras.find(cam => cam.deviceId === this.selectedCameraId);
if (selectedCamera) {
let label = selectedCamera.label || 'Selected Camera';
if (label.toLowerCase().includes('back') || label.toLowerCase().includes('rear')) {
label = '📷 Back Camera';
} else if (label.toLowerCase().includes('front')) {
label = '📱 Front Camera';
}
// Find and update the option
const option = this.cameraSelect.querySelector(`option[value="${this.selectedCameraId}"]`);
if (option) {
option.textContent = `${label} ✓`;
}
}
}
// Get actual video dimensions and calculate aspect ratio
const videoWidth = this.video.videoWidth;
const videoHeight = this.video.videoHeight;
this.aspectRatio = videoWidth / videoHeight;
console.log(`Camera resolution: ${videoWidth}x${videoHeight} (${this.aspectRatio.toFixed(2)}:1)`);
this.videoResolution.textContent = `${videoWidth}×${videoHeight}`;
this.startButton.disabled = true;
this.stopButton.disabled = false;
this.saveImageButton.disabled = false;
this.cameraSelect.disabled = true; // Disable camera selection while camera is active
this.status.textContent = 'Active';
this.status.className = 'status-indicator active';
this.updateToggleVideoButton();
this.startRendering();
this.startFPSCounter();
} catch (error) {
this.status.textContent = `Error: ${error.message}`;
this.status.className = 'status-indicator';
console.error('Camera error:', error);
// If specific camera failed, try to get any camera
if (this.selectedCameraId && error.name === 'OverconstrainedError') {
this.showAlert('Selected camera not available. Trying any available camera...', 'warning');
this.selectedCameraId = null;
this.cameraSelect.value = '';
setTimeout(() => this.startCamera(), 1000);
}
if (error.name === 'NotAllowedError') {
this.status.textContent = 'Camera permission denied';
this.showAlert('Camera permission is required. Please allow camera access.', 'error');
} else if (error.name === 'NotFoundError') {
this.status.textContent = 'No camera found';
this.showAlert('No camera device found. Please connect a camera.', 'error');
} else if (error.name === 'NotReadableError') {
this.status.textContent = 'Camera in use';
this.showAlert('Camera is already in use by another application.', 'error');
}
}
}
stopCamera() {
if (this.stream) {
this.stream.getTracks().forEach(track => track.stop());
this.stream = null;
}
if (this.animationId) {
cancelAnimationFrame(this.animationId);
this.animationId = null;
}
this.video.srcObject = null;
this.asciiOutput.textContent = '';
this.startButton.disabled = false;
this.stopButton.disabled = true;
this.saveImageButton.disabled = true;
this.cameraSelect.disabled = false; // Enable camera selection when camera stops
// Reset camera labels
this.resetCameraLabels();
this.status.textContent = 'Stopped';
this.status.className = 'status-indicator';
this.frameRate.textContent = '-';
this.videoResolution.textContent = '-';
}
resetCameraLabels() {
// Reset all camera labels to remove checkmarks
const options = this.cameraSelect.querySelectorAll('option');
options.forEach(option => {
if (option.value) {
const camera = this.availableCameras.find(cam => cam.deviceId === option.value);
if (camera) {
let label = camera.label || `Camera ${Array.from(options).indexOf(option)}`;
if (label.toLowerCase().includes('back') || label.toLowerCase().includes('rear')) {
label = '📷 Back Camera';
} else if (label.toLowerCase().includes('front')) {
label = '📱 Front Camera';
} else if (label.toLowerCase().includes('external')) {
label = '🔌 External Camera';
}
option.textContent = label;
}
}
});
}
updateToggleVideoButton() {
this.toggleVideoButton.innerHTML = this.showVideo ?
'<i class="fas fa-eye-slash"></i> Hide Video' :
'<i class="fas fa-eye"></i> Show Video';
}
toggleVideo() {
this.showVideo = !this.showVideo;
this.video.style.display = this.showVideo ? 'block' : 'none';
this.updateToggleVideoButton();
}
startRendering() {
const render = (timestamp) => {
if (!this.stream || this.isProcessing) {
this.animationId = requestAnimationFrame(render);
return;
}
// Calculate FPS
if (this.lastFrameTime) {
const delta = timestamp - this.lastFrameTime;
this.fps = Math.round(1000 / delta);
}
this.lastFrameTime = timestamp;
// Process frame
this.processFrame();
// Update display info
this.updateDisplayInfo();
this.animationId = requestAnimationFrame(render);
};
this.animationId = requestAnimationFrame(render);
}
startFPSCounter() {
setInterval(() => {
if (this.fps > 0) {
this.frameRate.textContent = `${this.fps} FPS`;
}
}, 1000);
}
calculateTargetDimensions() {
const resolution = this.resolutionSelect.value;
if (resolution === 'native') {
// For native resolution, we need to consider character aspect ratio
// We want to maintain the video's aspect ratio in the final ASCII output
const maxWidth = 240; // Maximum characters width for performance
// Calculate width based on video aspect ratio and character aspect
let targetWidth = Math.min(this.video.videoWidth / 8, maxWidth);
// Adjust height for character aspect ratio (characters are taller)
let targetHeight = Math.round(targetWidth / this.aspectRatio * this.characterAspectRatio);
return { width: Math.round(targetWidth), height: targetHeight };
} else {
// Use preset resolution (already adjusted for 16:9 and character aspect)
return this.resolutions[resolution];
}
}
processFrame() {
if (this.video.readyState !== this.video.HAVE_ENOUGH_DATA || !this.video.videoWidth) {
return;
}
this.isProcessing = true;
try {
// Calculate target dimensions considering aspect ratio
const { width: targetWidth, height: targetHeight } = this.calculateTargetDimensions();
// Set canvas dimensions
this.canvas.width = targetWidth;
this.canvas.height = targetHeight;
// Draw video to canvas with correct aspect ratio
this.ctx.imageSmoothingEnabled = false;
// Calculate source aspect ratio
const sourceAspect = this.video.videoWidth / this.video.videoHeight;
const targetAspect = targetWidth / targetHeight;
let sx, sy, sWidth, sHeight;
if (sourceAspect > targetAspect) {
// Source is wider - crop sides
sHeight = this.video.videoHeight;
sWidth = sHeight * targetAspect;
sx = (this.video.videoWidth - sWidth) / 2;
sy = 0;
} else {
// Source is taller - crop top/bottom
sWidth = this.video.videoWidth;
sHeight = sWidth / targetAspect;
sx = 0;
sy = (this.video.videoHeight - sHeight) / 2;
}
// Draw the image with cropping to maintain aspect ratio
this.ctx.drawImage(
this.video,
sx, sy, sWidth, sHeight,
0, 0, targetWidth, targetHeight
);
// Convert to ASCII
const asciiArt = this.convertToAscii(targetWidth, targetHeight);
// Store current ASCII
this.currentAsciiText = asciiArt;
// Update output with aspect ratio correction
this.asciiOutput.textContent = asciiArt;
this.asciiOutput.classList.add('aspect-corrected');
// Update ASCII resolution display
const lines = asciiArt.split('\n').filter(line => line.length > 0);
if (lines.length > 0) {
const asciiWidth = lines[0].length;
const asciiHeight = lines.length;
this.asciiResolution.textContent = `${asciiWidth}×${asciiHeight}`;
}
} catch (error) {
console.error('Frame processing error:', error);
} finally {
this.isProcessing = false;
}
}
convertToAscii(width, height) {
const imageData = this.ctx.getImageData(0, 0, width, height);
const data = imageData.data;
const style = this.asciiStyleSelect.value;
const chars = this.asciiChars[style] || this.asciiChars.detailed;
let asciiArt = '';
// For binary style, we can add simple dithering for better visual effect
if (style === 'binary') {
// Create a copy of the image data for dithering
const ditheredData = new Uint8ClampedArray(data);
// Simple Floyd-Steinberg dithering for better binary representation
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const idx = (y * width + x) * 4;
// Get old pixel value (brightness)
const oldR = ditheredData[idx];
const oldG = ditheredData[idx + 1];
const oldB = ditheredData[idx + 2];
const oldBrightness = 0.299 * oldR + 0.587 * oldG + 0.114 * oldB;
// Determine new pixel value (0 or 255)
const newBrightness = oldBrightness > 127 ? 255 : 0;
// Calculate quantization error
const error = oldBrightness - newBrightness;
// Update pixel
const factor = newBrightness / 255;
ditheredData[idx] = factor * 255;
ditheredData[idx + 1] = factor * 255;
ditheredData[idx + 2] = factor * 255;
// Distribute error to neighboring pixels (Floyd-Steinberg)
if (x + 1 < width) {
const rightIdx = idx + 4;
ditheredData[rightIdx] = Math.min(255, Math.max(0, ditheredData[rightIdx] + error * 7/16));
}
if (y + 1 < height) {
const downIdx = idx + width * 4;
if (x > 0) {
const downLeftIdx = downIdx - 4;
ditheredData[downLeftIdx] = Math.min(255, Math.max(0, ditheredData[downLeftIdx] + error * 3/16));
}
ditheredData[downIdx] = Math.min(255, Math.max(0, ditheredData[downIdx] + error * 5/16));
if (x + 1 < width) {
const downRightIdx = downIdx + 4;
ditheredData[downRightIdx] = Math.min(255, Math.max(0, ditheredData[downRightIdx] + error * 1/16));
}
}
}
}
// Convert dithered image to binary
for (let y = 0; y < height; y++) {
let line = '';
for (let x = 0; x < width; x++) {
const idx = (y * width + x) * 4;
const brightness = 0.299 * ditheredData[idx] + 0.587 * ditheredData[idx + 1] + 0.114 * ditheredData[idx + 2];
line += brightness > 127 ? '1' : '0';
}
asciiArt += line + '\n';
}
} else {
// Normal ASCII conversion for other styles
for (let y = 0; y < height; y++) {
let line = '';
for (let x = 0; x < width; x++) {
const index = (y * width + x) * 4;
const r = data[index];
const g = data[index + 1];
const b = data[index + 2];
// Calculate brightness (perceptual luminance)
const brightness = 0.299 * r + 0.587 * g + 0.114 * b;
const charIndex = Math.floor((brightness / 255) * (chars.length - 1));
line += chars[charIndex];
}
asciiArt += line + '\n';
}
}
return asciiArt;
}
updateResolution() {
const resolution = this.resolutionSelect.value;
const preset = this.resolutions[resolution];
if (resolution === 'native') {
this.currentResolution.textContent = 'Native (Full)';
} else {
this.currentResolution.textContent = `${preset.width}×${preset.height}`;
}
}
updateAsciiStyle() {
// Style will be applied on next render
}
updateDisplayInfo() {
if (this.currentAsciiText) {
const lines = this.currentAsciiText.split('\n').filter(line => line.length > 0);
if (lines.length > 0) {
const asciiWidth = lines[0].length;
const asciiHeight = lines.length;
this.asciiSize.textContent = `${asciiWidth}×${asciiHeight} chars`;
}
}
}
captureFrame() {
if (!this.stream || !this.currentAsciiText) {
this.showAlert('No camera feed available!', 'error');
return;
}
this.capturedAsciiText = this.currentAsciiText;
this.capturedAscii.textContent = this.capturedAsciiText;
// Format timestamp
const now = new Date();
const timestamp = now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
this.lastCapture.textContent = timestamp;
// Show modal
this.captureModal.style.display = 'flex';
this.showAlert('Frame captured!', 'success');
}
closeModal() {
this.captureModal.style.display = 'none';
}
async copyToClipboard() {
if (!this.currentAsciiText) {
this.showAlert('No ASCII art to copy!', 'error');
return;
}
try {
await navigator.clipboard.writeText(this.currentAsciiText);
this.showAlert('ASCII art copied to clipboard!', 'success');
} catch (error) {
console.error('Copy failed:', error);
this.showAlert('Failed to copy. Please select and copy manually.', 'error');
}
}
async copyCaptureToClipboard() {
if (!this.capturedAsciiText) {
this.showAlert('No captured frame to copy!', 'error');
return;
}
try {
await navigator.clipboard.writeText(this.capturedAsciiText);
this.showAlert('Captured frame copied to clipboard!', 'success');
} catch (error) {
console.error('Copy failed:', error);
this.showAlert('Failed to copy. Please select and copy manually.', 'error');
}
}
saveAsImage() {
if (!this.currentAsciiText) {
this.showAlert('No ASCII art to save!', 'error');
return;
}
this.captureFrame();
setTimeout(() => {
this.saveCaptureAsImage();
}, 100);
}
saveCaptureAsImage() {
if (!this.capturedAsciiText) {
this.showAlert('No captured frame to save!', 'error');
return;
}
// Create a canvas to render the ASCII art as an image
const lines = this.capturedAsciiText.split('\n').filter(line => line.length > 0);
if (lines.length === 0) return;
const asciiWidth = lines[0].length;
const asciiHeight = lines.length;
// Create canvas with appropriate size
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// Calculate canvas size (each character as 8x16 pixels)
const charWidth = 8;
const charHeight = 16;
canvas.width = asciiWidth * charWidth + 40; // Add padding
canvas.height = asciiHeight * charHeight + 40;
// Fill background
ctx.fillStyle = '#000000';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw ASCII text
ctx.font = `${charHeight}px 'Courier New', monospace`;
ctx.fillStyle = '#00ff00';
ctx.textBaseline = 'top';
// Add title and timestamp
const now = new Date();
const timestamp = now.toLocaleString();
ctx.fillText(`ASCII Camera - ${timestamp}`, 20, 10);
// Draw ASCII art
for (let y = 0; y < asciiHeight; y++) {
ctx.fillText(lines[y], 20, 30 + y * charHeight);
}
// Convert to data URL and download
const dataUrl = canvas.toDataURL('image/png');
const link = document.createElement('a');
link.download = `ascii-camera-${Date.now()}.png`;
link.href = dataUrl;
link.click();
this.showAlert('Image saved successfully!', 'success');
}
printAscii() {
if (!this.currentAsciiText) {
this.showAlert('No ASCII art to print!', 'error');
return;
}
this.captureFrame();
setTimeout(() => {
this.printCapture();
}, 100);
}
printCapture() {
if (!this.capturedAsciiText) {
this.showAlert('No captured frame to print!', 'error');
return;
}
// Create a printable window
const printWindow = window.open('', '_blank');
printWindow.document.write(`
<!DOCTYPE html>
<html>
<head>
<title>ASCII Camera Print</title>
<style>
body {
font-family: 'Courier New', monospace;
background: white;
color: black;
padding: 20px;
}
pre {
font-size: 4px;
line-height: 1;
white-space: pre;
margin: 0;
}
.header {
text-align: center;
margin-bottom: 20px;
border-bottom: 2px solid #000;
padding-bottom: 10px;
}
@media print {
body { padding: 0; }
.no-print { display: none; }
}
</style>
</head>
<body>
<div class="header">
<h1>ASCII Camera Capture</h1>
<p>Generated on ${new Date().toLocaleString()}</p>
</div>
<pre>${this.capturedAsciiText}</pre>
<div class="no-print" style="margin-top: 20px; text-align: center;">
<button onclick="window.print()">Print</button>
<button onclick="window.close()">Close</button>
</div>
</body>
</html>
`);
printWindow.document.close();
// Auto-print after a short delay
setTimeout(() => {
printWindow.print();
}, 500);
}
downloadAsText() {
if (!this.capturedAsciiText) {
this.showAlert('No captured frame to download!', 'error');
return;
}
const blob = new Blob([this.capturedAsciiText], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.download = `ascii-camera-${Date.now()}.txt`;
link.href = url;
link.click();
URL.revokeObjectURL(url);
this.showAlert('Text file downloaded!', 'success');
}
showAlert(message, type = 'info') {
// Remove existing alert
const existingAlert = document.querySelector('.alert');
if (existingAlert) {
existingAlert.remove();
}
// Create alert
const alert = document.createElement('div');
alert.className = `alert alert-${type}`;
alert.textContent = message;
alert.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
padding: 15px 25px;
border-radius: 10px;
background: ${type === 'error' ? 'var(--error-color)' :
type === 'success' ? 'var(--success-color)' : 'var(--surface-light)'};
color: ${type === 'error' || type === 'success' ? 'white' : 'var(--text-color)'};
border: 2px solid ${type === 'error' ? 'var(--error-color)' :
type === 'success' ? 'var(--success-color)' : 'var(--primary-color)'};
z-index: 10000;
font-weight: bold;
animation: fadeIn 0.3s ease;
`;
document.body.appendChild(alert);
// Auto-remove after 3 seconds
setTimeout(() => {
if (alert.parentNode) {
alert.style.opacity = '0';
alert.style.transition = 'opacity 0.5s ease';
setTimeout(() => {
if (alert.parentNode) {
alert.parentNode.removeChild(alert);
}
}, 500);
}
}, 3000);
}
}
// Initialize when page loads
document.addEventListener('DOMContentLoaded', () => {
const asciiCamera = new ASCIICamera();
// Add global error handler
window.addEventListener('error', (e) => {
console.error('Global error:', e.error);
});
});