-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
117 lines (93 loc) · 2.83 KB
/
index.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
let width = 320;
let height = 0;
let streaming = false;
let photo = null;
let canvas = null;
function startup() {
let video = document.getElementById("video");
canvas = document.getElementById("canvas");
let snip_button = document.getElementById("snap");
photo = document.getElementById("photo");
let flip_button = document.getElementById("flip");
//default user options
let stream = null;
let shouldFaceUser = true;
let defaultsOpts = { video: true, audio: false };
// Check if supports facingMode
let supports = navigator.mediaDevices.getSupportedConstraints();
if (supports["facingMode"] === true) {
flip_button.disabled = false;
}
// Get streaming media video without audio
let capture = function() {
// Check which camera will choose, front or back
defaultsOpts.video = {
facingMode: shouldFaceUser ? "user" : "environment"
};
//Activate camera
navigator.mediaDevices
.getUserMedia(defaultsOpts)
.then(_stream => {
stream = _stream;
video.srcObject = stream;
video.play();
})
.catch(error => console.error(error));
};
// Listen video to start playing
video.addEventListener("canplay", function(e) {
if (!streaming) {
height = video.videoHeight / (video.videoWidth / width);
//set width and height properties
video.setAttribute("width", 1280);
video.setAttribute("height", 320);
canvas.setAttribute("width", 50);
canvas.setAttribute("height", 50);
streaming = true;
}
},
false
);
//Snip Button
snip_button.addEventListener("click",function(e) {
takePicture();
e.preventDefault();
},
false
);
// Flip Button
flip_button.addEventListener("click", function() {
if (stream == null) return;
stream.getTracks().forEach(t => {
t.stop();
});
shouldFaceUser = !shouldFaceUser;
capture();
});
capture();
clearPicture();
}
// Fill the photo with an indication that none has been
// captured.
function clearPicture() {
let context = canvas.getContext("2d");
context.fillStyle = "#AAA";
context.fillRect(0, 0, canvas.width, canvas.height);
let data = canvas.toDataURL("image/png");
photo.setAttribute("src", data);
}
// Take Picture
function takePicture() {
let context = canvas.getContext("2d");
if (width && height) {
canvas.width = width;
canvas.height = height;
context.drawImage(video, 0, 0, width, height);
let data = canvas.toDataURL("image/png");
photo.setAttribute("src", data);
} else {
clearPicture();
}
}
//Run startup after loading
window.addEventListener("load", startup, false);