-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
68 lines (61 loc) · 2.38 KB
/
app.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
var frontCamera = false;
var currentStream;
// Define constants
// Get the element in the document with id="camera-view", "camera-device", "photo-display", "take-photo-button" and "front-camera-button"
const
cameraView = document.querySelector("#camera-view"),
cameraDevice = document.querySelector("#camera-device"),
photoDisplay = document.querySelector("#photo-display"),
takePhotoButton = document.querySelector("#take-photo-button");
frontCameraButton = document.querySelector("#front-camera-button");
// Access the device camera and stream to cameraDevice
function cameraStart() {
// Stop the video streaming before access the media device
if (typeof currentStream !== 'undefined') {
currentStream.getTracks().forEach(track => {
track.stop();
});
}
// Set constraints for the video stream
// If frontCamera is true, use front camera
// Otherwise, user back camera
// "user" => Front camera
// "environment" => Back camera
var constraints = { video: { facingMode: (frontCamera? "user" : "environment") }, audio: false };
// Access the media device, camera in this example
navigator.mediaDevices
.getUserMedia(constraints)
.then(function(stream) {
currentStream = stream;
cameraDevice.srcObject = stream;
})
.catch(function(error) {
console.error("Error happened.", error);
});
}
// If takePhotoButton clicked => Take and display a photo
takePhotoButton.onclick = function() {
cameraView.width = cameraDevice.videoWidth;
cameraView.height = cameraDevice.videoHeight;
cameraView.getContext("2d").drawImage(cameraDevice, 0, 0);
photoDisplay.src = cameraView.toDataURL("image/webp");
photoDisplay.classList.add("photo-taken");
};
// If Front/Back camera is click => Change to front/back camera accordingly
frontCameraButton.onclick = function() {
// Toggle the frontCamera variable
frontCamera = !frontCamera;
// Setup the button text
if (frontCamera) {
frontCameraButton.textContent = "Back Camera";
}
else {
frontCameraButton.textContent = "Front Camera";
}
// Start the video streaming
cameraStart();
};
// Start the camera and video streaming when the window loads
// 1st parameter: Event type
// 2nd parameter: Function to be called when the event occurs
window.addEventListener("load", cameraStart);