使用html5调用摄像头进行拍照(兼容各大浏览器)
页面html基本结构
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#video {
border: 1px solid #999;
display: block;
margin: 0 0 10px 0;
float:left;
}
#canvas {
border: 1px solid #999;
margin-top: 10px;
border: 1px solid #999;
display: block;
}
</style>
</head>
<body>
<button id="snap">拍照</button>
<video id="video" width="200" height="200" autoplay></video>
<canvas id="canvas" width="200" height="200"></canvas>
</body>
</html>
js代码
//获得Canvas对象
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
//获得video摄像头区域
var video = document.getElementById("video");
//当DOM树构建完成的时候就会执行DOMContentLoaded事件
window.addEventListener("DOMContentLoaded", function() {
var videoObj = {
"video": true
};
var errBack = function(error) {
console.log("Video capture error: ", error.code);
};
//获得摄像头并显示到video区域
if (navigator.webkitGetUserMedia) { // WebKit-prefixed
navigator.webkitGetUserMedia(videoObj, function(stream) {
video.src = window.webkitURL.createObjectURL(stream);
video.play();
}, errBack);
} else if (navigator.mozGetUserMedia) { // Firefox-prefixed
navigator.mozGetUserMedia(videoObj, function(stream) {
video.src = window.URL.createObjectURL(stream);
video.play();
}, errBack);
}
}, false);
// 触发拍照动作
document.getElementById("snap").addEventListener("click", function() {
context.drawImage(video, 0, 0, 200, 200);
});
测试
注意:新版chrome只能在https下才能调用该接口进行拍照!!!!
注意:新版chrome只能在https下才能调用该接口进行拍照!!!!
注意:新版chrome只能在https下才能调用该接口进行拍照!!!!