-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
81 lines (62 loc) · 2.21 KB
/
Copy pathscript.js
File metadata and controls
81 lines (62 loc) · 2.21 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
const video = document.querySelector('video');
const flashOverlay = document.getElementById('flashOverlay');
const snapBtn = document.getElementById('snapBtn');
const colorPicker = document.getElementById('colorPicker');
const canvasContainer = document.getElementById('canvasContainer');
async function startCamera() {
try {
const stream = await navigator.mediaDevices.getUserMedia({
video: {
facingMode: 'user',
width: { ideal: 2560 },
height: { ideal: 1920 }
}
});
video.srcObject = stream;
} catch (err) {
alert('Erro ao acessar a câmera: ' + err.message);
}
}
function takeSnapshot() {
const videoWidth = video.videoWidth;
const videoHeight = video.videoHeight;
const targetRatio = 3 / 4;
let cropWidth = videoWidth;
let cropHeight = videoHeight;
const videoRatio = videoWidth / videoHeight;
if (videoRatio > targetRatio) {
cropWidth = Math.floor(videoHeight * targetRatio);
} else if (videoRatio < targetRatio) {
cropHeight = Math.floor(videoWidth / targetRatio);
}
const canvas = document.createElement('canvas');
canvas.width = cropWidth;
canvas.height = cropHeight;
const ctx = canvas.getContext('2d');
ctx.save();
ctx.translate(cropWidth, 0);
ctx.scale(-1, 1);
const sx = Math.floor((videoWidth - cropWidth) / 2);
const sy = Math.floor((videoHeight - cropHeight) / 2);
ctx.drawImage(video, sx, sy, cropWidth, cropHeight, 0, 0, cropWidth, cropHeight);
ctx.restore();
return canvas;
}
snapBtn.addEventListener('click', () => {
const corFlash = colorPicker.value;
flashOverlay.style.backgroundColor = corFlash;
flashOverlay.style.opacity = '1';
setTimeout(() => {
flashOverlay.style.opacity = '0';
const canvas = takeSnapshot();
canvasContainer.innerHTML = '';
canvasContainer.appendChild(canvas);
const link = document.createElement('a');
link.href = canvas.toDataURL('image/png');
link.download = 'selfie-flash-colorido.png';
link.id = 'downloadBtn';
link.textContent = 'Download da Foto';
canvasContainer.appendChild(link);
}, 800);
});
startCamera();