Repository navigation
Expand file tree
/
Copy pathtext.js
More file actions
482 lines (442 loc) · 18 KB
/
Copy pathtext.js
File metadata and controls
482 lines (442 loc) · 18 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
// text.js
// Combined logic: camera features + Matrix background + AI results reveal animation
// Assumes the HTML IDs in index.html
/* ------------------ MATRIX RAIN EFFECT ------------------ */
(function initMatrix() {
const canvas = document.getElementById('matrixCanvas');
if (!canvas) return;
const ctx = canvas.getContext('2d');
let W = canvas.width = window.innerWidth;
let H = canvas.height = window.innerHeight;
const fontSize = 14; // size of each "drop" glyph
let columns = Math.floor(W / fontSize);
// characters used (binary + subtle symbols for ambience)
const letters = '01⚑✦✧'; // short set; adjust as desired
let drops = new Array(columns).fill(1);
function draw() {
// translucent black to create trail effect
ctx.fillStyle = 'rgba(0,0,0,0.06)';
ctx.fillRect(0, 0, W, H);
ctx.fillStyle = '#00ff66'; // neon green
ctx.font = fontSize + 'px monospace';
for (let i = 0; i < drops.length; i++) {
const text = letters[Math.floor(Math.random() * letters.length)];
ctx.fillText(text, i * fontSize, drops[i] * fontSize);
if (drops[i] * fontSize > H && Math.random() > 0.975) {
drops[i] = 0;
}
drops[i]++;
}
}
let matrixInterval = setInterval(draw, 45);
function resize() {
W = canvas.width = window.innerWidth;
H = canvas.height = window.innerHeight;
columns = Math.floor(W / fontSize);
drops = new Array(columns).fill(1);
}
window.addEventListener('resize', resize, { passive: true });
// Expose a simple API to pause/resume if needed later
window._matrixControl = {
pause: () => clearInterval(matrixInterval),
resume: () => { matrixInterval = setInterval(draw, 45); }
};
})();
/* ------------------ CAMERA + APP LOGIC (adapted from your provided code) ------------------ */
const cameraFeed = document.getElementById('cameraFeed');
const snapshotCanvas = document.getElementById('snapshotCanvas');
const timestampOverlay = document.getElementById('timestampOverlay');
const countdownDisplay = document.getElementById('countdownDisplay');
const snapshotBtn = document.getElementById('snapshotBtn');
const recordBtn = document.getElementById('recordBtn');
const stopRecordBtn = document.getElementById('stopRecordBtn');
const fullscreenBtn = document.getElementById('fullscreenBtn');
const zoomInBtn = document.getElementById('zoomInBtn');
const zoomOutBtn = document.getElementById('zoomOutBtn');
const settingsBtn = document.getElementById('settingsBtn');
const settingsPanel = document.getElementById('settingsPanel');
const flashToggle = document.getElementById('flashToggle');
const audioToggle = document.getElementById('audioToggle');
const resolutionSelect = document.getElementById('resolutionSelect');
const filterBtns = document.querySelectorAll('.filterBtn');
const aiResults = document.getElementById('aiResults');
const objectsList = document.getElementById('objectsList');
const labelsList = document.getElementById('labelsList');
const cameraContainer = document.getElementById('cameraContainer');
let stream = null;
let videoTrack = null;
let audioTrack = null;
let drawRaf = null;
let audioContext = null;
let currentFilter = 'none';
let zoomLevel = 1;
let supportsZoom = false;
let useHardwareTorch = false;
let isCountingDown = false;
let countdownInterval = null;
// canvas used for compositing
const ctx = snapshotCanvas.getContext ? snapshotCanvas.getContext('2d') : null;
const RECORD_FPS = 30;
/* ---------- audio helpers ---------- */
function ensureAudioContext(){
if (audioContext) return;
try{ audioContext = new (window.AudioContext || window.webkitAudioContext)(); }
catch(e){ audioContext = null; }
}
function playSound(freq=440, duration=160){
if (!audioContext || !audioToggle.checked) return;
const o = audioContext.createOscillator();
const g = audioContext.createGain();
o.connect(g); g.connect(audioContext.destination);
o.frequency.value = freq; o.type = 'sine';
const now = audioContext.currentTime;
g.gain.setValueAtTime(0.2, now);
g.gain.exponentialRampToValueAtTime(0.001, now + duration/1000);
o.start(now); o.stop(now + duration/1000 + 0.02);
}
/* ---------- timestamp UI ---------- */
function updateTimestampUI(){
const now = new Date();
timestampOverlay.textContent = now.toLocaleTimeString();
}
/* ---------- filter mapping ---------- */
function buildFilterString(){
switch(currentFilter){
case 'grayscale': return 'grayscale(100%)';
case 'sepia': return 'sepia(100%)';
case 'invert': return 'invert(100%)';
case 'blur': return 'blur(4px)';
default: return 'none';
}
}
/* ---------- draw video to snapshotCanvas continuously ---------- */
function drawFrameToCanvas(){
if (!cameraFeed || cameraFeed.readyState < 2) {
drawRaf = requestAnimationFrame(drawFrameToCanvas);
return;
}
const vw = cameraFeed.videoWidth || cameraFeed.clientWidth;
const vh = cameraFeed.videoHeight || cameraFeed.clientHeight;
if (snapshotCanvas.width !== vw || snapshotCanvas.height !== vh){
snapshotCanvas.width = vw;
snapshotCanvas.height = vh;
}
// apply filter and draw
try {
ctx.filter = buildFilterString();
ctx.drawImage(cameraFeed, 0, 0, snapshotCanvas.width, snapshotCanvas.height);
} catch(e){
// drawing can fail briefly; ignore
}
// draw timestamp into canvas (bottom-left)
ctx.filter = 'none';
const fontSize = Math.max(14, Math.floor(snapshotCanvas.width * 0.03));
ctx.font = `${fontSize}px sans-serif`;
ctx.fillStyle = 'rgba(0,0,0,0.6)';
ctx.fillRect(10, snapshotCanvas.height - (fontSize + 18), 200, fontSize + 12);
ctx.fillStyle = '#fff';
ctx.textBaseline = 'middle';
ctx.fillText(new Date().toLocaleTimeString(), 18, snapshotCanvas.height - (fontSize/2 + 6));
drawRaf = requestAnimationFrame(drawFrameToCanvas);
}
/* ---------- snapshot (downloads image) ---------- */
async function takeSnapshot(){
drawFrameToCanvas(); // ensure latest frame
if (flashToggle.checked) await simulateFlashOverlay(120);
snapshotCanvas.toBlob((blob) => {
if (!blob) return;
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `snapshot_${new Date().toISOString().replace(/[:.]/g,'-')}.jpg`;
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
playSound(660, 240);
// fire AI analysis in background
analyzeImage(); // no await
}, 'image/jpeg', 0.92);
}
/* ---------- simulate flash overlay ---------- */
function simulateFlashOverlay(duration = 120){
return new Promise(resolve => {
const overlay = document.createElement('div');
overlay.style.position = 'absolute';
overlay.style.inset = '0';
overlay.style.background = '#ffffff';
overlay.style.opacity = '0.95';
overlay.style.pointerEvents = 'none';
overlay.style.zIndex = '9999';
cameraContainer.appendChild(overlay);
setTimeout(()=> {
cameraContainer.removeChild(overlay);
resolve();
}, duration);
});
}
/* ---------- AI analysis (example: POST to /analyze-image) ---------- */
async function analyzeImage(){
try {
const dataUrl = snapshotCanvas.toDataURL('image/jpeg', 0.9);
const response = await fetch('http://localhost:3000/analyze-image', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ image: dataUrl })
});
if (!response.ok) throw new Error('AI server error');
const result = await response.json();
displayResults(result);
} catch (err) {
console.warn('AI analysis failed (skipping):', err);
// fallback: show placeholder if desired
displayResults({
objects: [{ name: 'placeholder object', confidence: 0.86 }],
labels: [{ description: 'example label', confidence: 0.73 }]
});
}
}
/* ---------- Display AI results with animated reveal (staggered) ---------- */
function displayResults(result){
// clear lists
objectsList.innerHTML = '';
labelsList.innerHTML = '';
// populate objects
if (result.objects && Array.isArray(result.objects)){
result.objects.forEach((obj, idx) => {
const li = document.createElement('li');
li.className = 'ai-item';
li.textContent = `${obj.name} (Confidence: ${(obj.confidence * 100).toFixed(1)}%)`;
// set staggered animation delay
li.style.animationDelay = `${idx * 0.12}s`;
objectsList.appendChild(li);
});
}
// populate labels
if (result.labels && Array.isArray(result.labels)){
result.labels.forEach((label, idx) => {
const li = document.createElement('li');
li.className = 'ai-item';
li.textContent = `${label.description} (Confidence: ${(label.confidence * 100).toFixed(1)}%)`;
// offset label delays a bit after objects
li.style.animationDelay = `${( (result.objects?.length || 0) * 0.12) + idx * 0.12}s`;
labelsList.appendChild(li);
});
}
// reveal container: make display block then add class (so transition runs)
aiResults.style.display = 'block';
// small timeout to ensure CSS transition sees the state change
requestAnimationFrame(() => {
aiResults.classList.add('show');
});
// auto-scroll into view on small screens
setTimeout(() => {
aiResults.scrollIntoView({ behavior: 'smooth', block: 'end' });
}, 400);
}
/* ---------- Recording (canvas-based) ---------- */
let mediaRecorder = null;
let recordedChunks = [];
async function startRecording(){
if (mediaRecorder && mediaRecorder.state === 'recording') return;
// optional audio
let audioStream = null;
if (audioToggle.checked) {
try {
audioStream = await navigator.mediaDevices.getUserMedia({ audio: true });
audioTrack = audioStream.getAudioTracks()[0];
} catch(e){
audioTrack = null;
}
}
const canvasStream = snapshotCanvas.captureStream(RECORD_FPS);
if (audioTrack) canvasStream.addTrack(audioTrack);
const options = MediaRecorder.isTypeSupported && MediaRecorder.isTypeSupported('video/webm;codecs=vp9,opus') ? { mimeType: 'video/webm;codecs=vp9,opus' } : undefined;
try {
mediaRecorder = new MediaRecorder(canvasStream, options);
} catch (err) {
try { mediaRecorder = new MediaRecorder(canvasStream); } catch(e) { alert('Recording unavailable'); return; }
}
recordedChunks = [];
mediaRecorder.ondataavailable = e => { if (e.data.size) recordedChunks.push(e.data); };
mediaRecorder.onstop = () => {
const blob = new Blob(recordedChunks, { type: mediaRecorder.mimeType || 'video/webm' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `recording_${new Date().toISOString().replace(/[:.]/g,'-')}.webm`;
document.body.appendChild(a); a.click(); a.remove();
URL.revokeObjectURL(url);
if (audioTrack) { audioTrack.stop(); audioTrack = null; }
};
mediaRecorder.start();
recordBtn.style.display = 'none';
stopRecordBtn.style.display = 'inline-block';
playSound(520, 200);
}
function stopRecording(){
if (mediaRecorder && mediaRecorder.state === 'recording') mediaRecorder.stop();
recordBtn.style.display = 'inline-block';
stopRecordBtn.style.display = 'none';
}
/* ---------- Countdown helper ---------- */
function disableControlsDuringCountdown(disable){
snapshotBtn.disabled = disable;
recordBtn.disabled = disable;
settingsBtn.disabled = disable;
}
function startCountdown(callback, duration = 3){
if (isCountingDown) return;
isCountingDown = true;
let count = duration;
countdownDisplay.textContent = count;
countdownDisplay.style.display = 'flex';
countdownDisplay.setAttribute('aria-hidden', 'false');
disableControlsDuringCountdown(true);
countdownInterval = setInterval(() => {
count--;
if (count > 0) {
countdownDisplay.textContent = count;
playSound(880, 120);
} else {
clearInterval(countdownInterval);
countdownInterval = null;
countdownDisplay.style.display = 'none';
countdownDisplay.setAttribute('aria-hidden', 'true');
disableControlsDuringCountdown(false);
isCountingDown = false;
playSound(880, 260);
callback();
}
}, 1000);
}
function cancelCountdown(){
if (!isCountingDown) return;
clearInterval(countdownInterval);
countdownInterval = null;
countdownDisplay.style.display = 'none';
disableControlsDuringCountdown(false);
isCountingDown = false;
}
/* ---------- zoom, torch, filters, resolution, fullscreen ---------- */
async function initZoomCapabilities(){
if (!stream) return;
videoTrack = stream.getVideoTracks()[0];
if (!videoTrack || typeof videoTrack.getCapabilities !== 'function') { supportsZoom = false; return; }
const caps = videoTrack.getCapabilities();
supportsZoom = !!caps.zoom;
}
async function setHardwareZoom(value){
if (!videoTrack || !supportsZoom) return false;
try { await videoTrack.applyConstraints({ advanced: [{ zoom: value }] }); zoomLevel = value; return true; }
catch(e){ return false; }
}
async function zoomIn(){
ensureAudioContext();
if (supportsZoom) {
await setHardwareZoom(Math.min(3, zoomLevel + 0.1));
} else {
zoomLevel = Math.min(3, zoomLevel + 0.1);
cameraFeed.style.transform = `scale(${zoomLevel})`;
}
playSound(523, 160);
}
async function zoomOut(){
ensureAudioContext();
if (supportsZoom) {
await setHardwareZoom(Math.max(1, zoomLevel - 0.1));
} else {
zoomLevel = Math.max(1, zoomLevel - 0.1);
cameraFeed.style.transform = `scale(${zoomLevel})`;
}
playSound(392, 160);
}
async function initTorchCapability(){
if (!stream) return;
videoTrack = stream.getVideoTracks()[0];
if (!videoTrack || typeof videoTrack.getCapabilities !== 'function') { useHardwareTorch = false; return; }
useHardwareTorch = !!videoTrack.getCapabilities().torch;
}
async function toggleTorch(enable){
if (!videoTrack) return false;
try { await videoTrack.applyConstraints({ advanced: [{ torch: !!enable }] }); return true; } catch(e){ return false; }
}
async function changeResolution(){
const [w,h] = resolutionSelect.value.split('x').map(v => parseInt(v,10));
await startCamera({ video: { facingMode: 'environment', width: { ideal: w }, height: { ideal: h } }, audio: false });
playSound(494, 200);
}
function toggleFullscreen(){
if (!document.fullscreenElement) {
cameraContainer.requestFullscreen?.();
} else {
document.exitFullscreen?.();
}
}
/* ---------- apply filters ---------- */
function applyFilter(filterName){
currentFilter = filterName || 'none';
cameraFeed.style.filter = buildFilterString();
playSound(440, 160);
}
/* ---------- camera start/stop ---------- */
async function startCamera(constraints = { video: { facingMode: 'environment', width: { ideal: 1280 }, height: { ideal: 720 } }, audio: false }){
if (stream) { stream.getTracks().forEach(t => t.stop()); stream = null; videoTrack = null; audioTrack = null; }
try {
stream = await navigator.mediaDevices.getUserMedia(constraints);
cameraFeed.srcObject = stream;
cameraFeed.playsInline = true;
await cameraFeed.play();
videoTrack = stream.getVideoTracks()[0] || null;
audioTrack = stream.getAudioTracks()[0] || null;
await initZoomCapabilities();
await initTorchCapability();
if (!drawRaf) drawFrameToCanvas();
setInterval(updateTimestampUI, 1000);
ensureAudioContext();
} catch(err){
console.error('Camera error', err);
alert('Could not access camera. Check permissions.');
}
}
/* ---------- Event wiring ---------- */
function handleUserGesture(){
ensureAudioContext();
if (audioContext && audioContext.state === 'suspended') audioContext.resume().catch(()=>{});
}
snapshotBtn.addEventListener('click', (e) => {
handleUserGesture();
if (isCountingDown) { cancelCountdown(); return; }
startCountdown(takeSnapshot, 3);
});
countdownDisplay.addEventListener('click', cancelCountdown);
recordBtn.addEventListener('click', () => {
handleUserGesture();
if (isCountingDown) { cancelCountdown(); return; }
startCountdown(startRecording, 3);
});
stopRecordBtn.addEventListener('click', stopRecording);
fullscreenBtn.addEventListener('click', toggleFullscreen);
zoomInBtn.addEventListener('click', zoomIn);
zoomOutBtn.addEventListener('click', zoomOut);
settingsBtn.addEventListener('click', () => {
settingsPanel.style.display = settingsPanel.style.display === 'none' ? 'block' : 'none';
playSound(330, 120);
});
resolutionSelect.addEventListener('change', changeResolution);
filterBtns.forEach(btn => btn.addEventListener('click', () => applyFilter(btn.dataset.filter || 'none')));
flashToggle.addEventListener('change', async () => {
if (flashToggle.checked && useHardwareTorch) { await toggleTorch(true); await toggleTorch(false); }
});
audioToggle.addEventListener('change', () => { if (audioToggle.checked) handleUserGesture(); });
document.addEventListener('keydown', (e) => {
if (e.code === 'Space') { e.preventDefault(); snapshotBtn.click(); }
});
/* ---------- init on load ---------- */
startCamera({ video: { facingMode: 'environment', width: { ideal: 1280 }, height: { ideal: 720 } }, audio: false });
window.addEventListener('beforeunload', () => {
if (stream) stream.getTracks().forEach(t => t.stop());
if (audioTrack) audioTrack.stop();
if (mediaRecorder && mediaRecorder.state === 'recording') mediaRecorder.stop();
if (drawRaf) cancelAnimationFrame(drawRaf);
});