-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdemo.html
84 lines (79 loc) · 3.03 KB
/
demo.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>拍照2</title>
</head>
<body>
<button id="open">调用摄像头</button>
<button id="take">拍照</button>
<button id="close">关闭摄像头</button>
<br />
<canvas id="canvas" style="display: none"></canvas>
<img src="http://placehold.it/640&text=Your%20image%20here%20..." id="photo" alt="photo" />
<video id="v" style="width: 640px; height: 480px; display: none"></video>
<br />
<script>
const take = document.getElementById('take');
const open = document.getElementById('open');
const close = document.getElementById('close');
const v = document.getElementById('v');
// 老的浏览器可能根本没有实现 mediaDevices,所以我们可以先设置一个空的对象
if (navigator.mediaDevices === undefined) {
navigator.mediaDevices = {};
}
if (navigator.mediaDevices.getUserMedia === undefined) {
navigator.mediaDevices.getUserMedia = function (constraints) {
// 首先,如果有getUserMedia的话,就获得它
var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
// 一些浏览器根本没实现它 - 那么就返回一个error到promise的reject来保持一个统一的接口
if (!getUserMedia) {
return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
}
// 否则,为老的navigator.getUserMedia方法包裹一个Promise
return new Promise(function (resolve, reject) {
getUserMedia.call(navigator, constraints, resolve, reject);
});
};
}
const constraints = { video: true, audio: false };
let videoPlaying = false;
let testStream;
open.onclick = async () => {
try {
testStream = await navigator.mediaDevices.getUserMedia(constraints);
v.style.display = 'block';
if ('srcObject' in v) {
v.srcObject = testStream;
} else {
// 防止再新的浏览器里使用它,应为它已经不再支持了
v.src = window.URL.createObjectURL(testStream);
}
v.onloadedmetadata = function (e) {
v.play();
videoPlaying = true;
};
} catch (error) {
console.error(error.name + ': ' + error.message);
}
};
close.onclick = () => {
v.src = '';
v.style.display = 'none';
testStream.getTracks().forEach(function (track) {
track.stop();
});
};
take.onclick = () => {
if (videoPlaying) {
let canvas = document.getElementById('canvas');
canvas.width = v.videoWidth;
canvas.height = v.videoHeight;
canvas.getContext('2d').drawImage(v, 0, 0);
let data = canvas.toDataURL('image/webp');
document.getElementById('photo').setAttribute('src', data);
}
};
</script>
</body>
</html>