HTML调用PC摄像头

使用HTML5中的canvas和video技术实现调用PC摄像头

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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML5调用电脑摄像头实例</title>
<script type="text/javascript">
window.addEventListener("DOMContentLoaded", function() {
// Grab elements, create settings, etc.
var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d"),
video = document.getElementById("video"),
videoObj = { "video": true },
errBack = function(error) {
console.log("Video capture error: ", error.code);
};

// Put video listeners into place
if(navigator.getUserMedia) { // Standard
//alert("支持navigator.getUserMedia");
navigator.getUserMedia(videoObj, function(stream) {
video.src = stream;
video.play();
}, errBack);
} else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
//alert("支持navigator.webkitGetUserMedia");
navigator.webkitGetUserMedia(videoObj, function(stream){
video.src = window.webkitURL.createObjectURL(stream);
video.play();
}, errBack);
}
else if(navigator.mozGetUserMedia) { // Firefox-prefixed
//alert("支持navigator.mozGetUserMedia");
navigator.mozGetUserMedia(videoObj, function(stream){
video.src = window.URL.createObjectURL(stream);
video.play();
}, errBack);
}
// 触发拍照动作
document.getElementById("snap").addEventListener("click", function() {
context.drawImage(video, 0, 0, 640, 480);
});

}, false);
</script>

</head>
<body>
<video id="video" width="640" height="480" autoplay></video><br>
<button id="snap" >点击拍照</button> <br>
<canvas id="canvas" width="640" height="480"></canvas>
</body>
</html>