第一步,调用摄像头,并且将摄像头捕获的画面,显示到网页上
主要用到的方法:
1.MediaDevices.getUserMedia(),参考地址:https://developer.mozilla.org/zh-CN/docs/Web/API/MediaDevices/getUserMedia
2.window.URL ,参考地址:
3.video.srcObject ,参考地址:https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/srcObject
贴上源码:集合到一个.html文件内,我是在笔记本上跑的,如果出现问题请打开控制台查看问题原因
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>Documenttitle>
head>
<body>
<video id="video" autoplay style="width: 480px;height: 320px">video>
<div>
<button id="capture">拍照button>
div>
<canvas id="canvas" width="480px" height="320px">canvas>
body>
html>
<script>
//dom
let video = document.getElementById('video');
let canvas = document.getElementById('canvas');
let capture = document.getElementById('capture');
let context = canvas.getContext('2d');
// getUserMediaToPhoto函数是自己定义的,传入3个参数
// 第一个参数constraints是一个对象,指定了请求的媒体类型和相对应的参数,针对本项目讲,就是设置视频的宽高
// 参考MDN:https://developer.mozilla.org/zh-CN/docs/Web/API/MediaDevices/getUserMedia
// 第二个参数:success,是成功回调函数
// 第三个参数:error,是抛出错误函数,具体又分为:没有获取到用户视频权限 和 浏览器不支持,分别在控制台输出提示
function getUserMediaToPhoto(constraints, success, error) {
if (navigator.mediaDevices.getUserMedia) {
//最新标准API 参考MDN:https://developer.mozilla.org/zh-CN/docs/Web/API/MediaDevices/getUserMedia
// 在绝大多数情况下,会调用这个方法,.then .catch是Promise的方法
// 传入第一个参数,constraints,然后执行.then 然后执行success方法 参考MDN:https://developer.mozilla.org/zh-CN/docs/Web/API/MediaDevices/getUserMedia#%E7%A4%BA%E4%BE%8B
navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error);
} else if (navigator.webkitGetUserMedia) {
//webkit核心浏览器,针对不同浏览器,调用浏览器的获取用户媒体的方法
navigator.webkitGetUserMedia(constraints, success, error);
} else if (navigator.mozGetUserMedia) {
//firefox浏览器
navigator.mozGetUserMedia(constraints, success, error);
} else if (navigator.getUserMedia) {
//旧版API
navigator.getUserMedia(constraints, success, error);
}
}
//成功回调函数
function success(stream) {
//兼容webkit核心浏览器 window.URL主要作用是读取文件的字符串,在img或video等带有src属性的标签上展示。
var CompatibleURL = window.URL || window.webkitURL;
//将视频流转化为video的源
// video.src = CompatibleURL.createObjectURL(stream);
video.srcObject = stream;
video.play();//播放视频
console.log(video.srcObject);
}
function error(error) {
console.log('访问用户媒体失败:', error.name, error.message);
document.write("访问用户媒体失败!")
}
if (navigator.mediaDevices.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia) {
getUserMediaToPhoto({ video: { width: 480, height: 320 } }, success, error);
} else {
alert('你的浏览器不支持访问用户媒体设备');
}
capture.addEventListener('click', function () {
// 将video画面描绘在canvas画布上
context.drawImage(video, 0, 0, 480, 320);
})
script>