-
Notifications
You must be signed in to change notification settings - Fork 42
/
script.js
97 lines (84 loc) · 2.38 KB
/
script.js
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
(function () {
if (
!"mediaDevices" in navigator ||
!"getUserMedia" in navigator.mediaDevices
) {
alert("Camera API is not available in your browser");
return;
}
// get page elements
const video = document.querySelector("#video");
const btnPlay = document.querySelector("#btnPlay");
const btnPause = document.querySelector("#btnPause");
const btnScreenshot = document.querySelector("#btnScreenshot");
const btnChangeCamera = document.querySelector("#btnChangeCamera");
const screenshotsContainer = document.querySelector("#screenshots");
const canvas = document.querySelector("#canvas");
const devicesSelect = document.querySelector("#devicesSelect");
// video constraints
const constraints = {
video: {
width: {
min: 1280,
ideal: 1920,
max: 2560,
},
height: {
min: 720,
ideal: 1080,
max: 1440,
},
},
};
// use front face camera
let useFrontCamera = true;
// current video stream
let videoStream;
// handle events
// play
btnPlay.addEventListener("click", function () {
video.play();
btnPlay.classList.add("is-hidden");
btnPause.classList.remove("is-hidden");
});
// pause
btnPause.addEventListener("click", function () {
video.pause();
btnPause.classList.add("is-hidden");
btnPlay.classList.remove("is-hidden");
});
// take screenshot
btnScreenshot.addEventListener("click", function () {
const img = document.createElement("img");
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext("2d").drawImage(video, 0, 0);
img.src = canvas.toDataURL("image/png");
screenshotsContainer.prepend(img);
});
// switch camera
btnChangeCamera.addEventListener("click", function () {
useFrontCamera = !useFrontCamera;
initializeCamera();
});
// stop video stream
function stopVideoStream() {
if (videoStream) {
videoStream.getTracks().forEach((track) => {
track.stop();
});
}
}
// initialize
async function initializeCamera() {
stopVideoStream();
constraints.video.facingMode = useFrontCamera ? "user" : "environment";
try {
videoStream = await navigator.mediaDevices.getUserMedia(constraints);
video.srcObject = videoStream;
} catch (err) {
alert("Could not access the camera");
}
}
initializeCamera();
})();