最近公司要做的项目是一个人脸识别门禁系统,期间需要用到使用浏览器调用电脑摄像头拍照的功能,网上搜到的大多已经过时,调用不了,于是自己写了一个可以用的,分享一波。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<video id="video" autoplay="" style='width:640px;height:480px'></video>
<button id="start">开启摄像头</button>
<button id='picture'>拍照</button>
<canvas id="canvas" width="640" height="480"></canvas>
</body>
<script type="text/javascript">
var video = document.getElementById("video");
var context = canvas.getContext("2d")
var start = document.getElementById("start");
var errocb = function () {
console.log('ok!');
}
start.onclick = function () {
if (navigator.mediaDevices.getUserMedia) { // 标准的API
var p = navigator.mediaDevices.getUserMedia({
video: true
});
p.then(function (mediaStream) {
var video = document.querySelector('video');
video.src = window.URL.createObjectURL(mediaStream);
video.onloadedmetadata = function (e) {
// Do something with the video here.
video.play();
};
});
p.catch(function(err) { console.log(err.name); });
} else if (navigator.mediaDevices.webkitGetUserMedia) { // WebKit
var p = navigator.mediaDevices.webkitGetUserMedia({
video: true
});
p.then(function (mediaStream) {
var video = document.querySelector('video');
video.src = window.URL.createObjectURL(mediaStream);
video.onloadedmetadata = function (e) {
// Do something with the video here.
video.play();
};
});
p.catch(function(err) { console.log(err.name); });
}
document.getElementById("picture").addEventListener("click", function () {
context.drawImage(video, 0, 0, 640, 480);
});
}
</script>
</html>
测试用的代码,主流的新版浏览器都可以用。
由于我这个管理系统采用的require+bootstrap,使用摄像头时还踩了一个小坑,报出了 “getContext is not define”的错误
解决方法是将 js代码直接写入canvas标签内,让js能够找到canvas对象
<canvas>调用摄像头的js代码</canvas>