此处获取电脑摄像头画面,并通过video标签展示画面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>获取电脑摄像头权限及其拍照</title>
</head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<style>
</style>
<body>
<div class="comtainer">
<video id="video" width="480" height="320" autoplay></video>
<canvas id="canvas" width="480" height="320" style="display: none;"></canvas>
<img src="" alt="默认照片" title="显示异常" id="img" width="480" height="320" style="margin-left: 20px;">
<div>
<button id="capture" title="点击进行拍照">拍照</button>
</div>
<div>
<button id="confirm" title="是否使用这张图片进行验证">确认</button>
</div>
</div>
</body>
<script>
var file, stream
/*
访问用户媒体设备的兼容方法
constraints 参数
success 成功回调
error 失败回调
*/
function getUserMedia (constraints, success, error) {
// 会提示用户给予使用媒体输入的许可
if (navigator.mediaDevices.getUserMedia) {
// 最新标准API
navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error);
} else if (navigator.webkitGetUserMedia) {
// webkit核心浏览器
navigator.webkitGetUserMedia (constraints, success, error)
} else if (navigator.mozGetUserMedia) {
// firfox浏览器
navigator.mozGetUserMedia (constraints, success, error)
} else if (navigator.getUserMedia) {
// 兼容旧版本API
navigator.getUserMedia (constraints, success, error)
} else {
alert ('该浏览器不支持获取摄像头权限')
}
}
// 获取video, canvas DOM元素
let video = document.getElementById('video')
let canvas = document.getElementById('canvas')
let context = canvas.getContext('2d')
//成功回调
function success (stream) {
// 兼容webkit核心浏览器
let CompatibleURL = window.URL || window.webkitURL
// 将视频流设置为video元素的源
console.log(stream)
stream = stream
video.srcObject = stream
video.play()
}
// 失败回调
function error (error) {
console.log(`访问用户媒体设备失败${error.name}, ${error.message}`);
}
if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {
// 调用用户媒体设备, 访问摄像头
getUserMedia ({video : {width: 480, height: 320}}, success, error)
} else {
alert('不支持访问用户媒体')
}
</script>
</html>