-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathapp.js
More file actions
95 lines (77 loc) · 2.59 KB
/
app.js
File metadata and controls
95 lines (77 loc) · 2.59 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
'use strict';
var message = {},
wrapper = {},
buttonNewPhoto = {},
buttonDownload = {},
video = {},
canvas = {};
function initElement() {
message = document.getElementById('msg');
wrapper = document.getElementById('wrapper');
buttonNewPhoto = document.getElementById('newphoto');
buttonDownload = document.getElementById('download');
video = document.querySelector('video');
canvas = document.querySelector('canvas');
if (navigator.mediaDevices === undefined) {
navigator.mediaDevices = {};
}
if (navigator.mediaDevices.getUserMedia === undefined) {
navigator.mediaDevices.getUserMedia = function (constraints) {
var getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
if (!getUserMedia) {
return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
}
return new Promise(function (resolve, reject) {
getUserMedia.call(navigator, constraints, resolve, reject);
})
}
}
}
function onTakeAPhoto() {
canvas.getContext('2d').drawImage(video, 0, 0, video.width, video.height);
buttonDownload.removeAttribute('disabled');
}
function onDownloadPhoto() {
canvas.toBlob(function (blob) {
var link = document.createElement('a');
link.download = 'photo.jpg';
link.setAttribute('href', URL.createObjectURL(blob));
link.dispatchEvent(new MouseEvent('click'));
}, 'image/jpeg', 1);
}
function onLoadVideo() {
video.setAttribute('width', this.videoWidth);
video.setAttribute('height', this.videoHeight);
canvas.setAttribute('width', this.videoWidth);
canvas.setAttribute('height', this.videoHeight);
video.play();
}
function onMediaStream(stream) {
if ('srcObject' in video) {
video.srcObject = stream;
} else {
video.src = window.URL.createObjectURL(stream);
}
message.style.display = 'none';
wrapper.style.display = 'block';
buttonNewPhoto.addEventListener('click', onTakeAPhoto);
buttonDownload.addEventListener('click', onDownloadPhoto);
video.addEventListener('loadedmetadata', onLoadVideo);
}
function onMediaError(err) {
message.innerHTML = err.name + ': ' + err.message;
}
function initEvent() {
navigator.mediaDevices
.getUserMedia({ video: true })
.then(onMediaStream)
.catch(onMediaError);
}
function init() {
initElement();
initEvent();
}
if (window.location.protocol != 'https:' && window.location.protocol != 'file:') {
window.location.href = 'https:' + window.location.href.substring(window.location.protocol.length);
}
window.addEventListener('DOMContentLoaded', init);