介绍
HTML5 的 getUserMedia API 为用户提供访问硬件设备媒体(摄像头、视频、音频、地理位置等)的接口,基于该接口,开发者可以在不依赖任何浏览器插件的条件下访问硬件媒体设备。
另外,主流浏览器 Firefox、Chrome、Safari、Opera 等等已经全面支持。
一、获取视频流,并用 video 标签播放
<video id="video" autoplay></video>
const videoConstraints = {width: 1366, height: 768 };const videoNode = document.querySelector('#video');let stream = await navigator.mediaDevices.getUserMedia({audio: true, video: videoConstraints });videoNode.srcObject = stream;videoNode.play();
二、多个摄像头设备切换
// enumerateDevices获取所有媒体设备const mediaDevices = await navigator.mediaDevices.enumerateDevices();// 通过设备实例king属性videoinput,过滤获取摄像头设备const videoDevices = mediaDevices.filter(item => item.kind === 'videoinput') || [];// 获取前置摄像头const videoDeviceId = videoDevices[0].deviceId;const videoConstraints = {deviceId: {exact: videoDeviceId }, width: 1366, height: 768 };let stream = await navigator.mediaDevices.getUserMedia({audio: true, video: videoConstraints });// 获取后置摄像头const videoDeviceId = videoDevices[1].deviceId;const videoConstraints = {deviceId: {exact: videoDeviceId }, width: 1366, height: 768 };let stream = await navigator.mediaDevices.getUserMedia({audio: true, video: videoConstraints });// 依次类推...
三、拍照保存图片
// 通过canvas捕捉video流,生成base64格式图片const canvas = document.createElement('canvas');const context = canvas.getContext('2d');canvas.width = 1366;canvas.height = 768;context.drawImage(videoNode, 0, 0, canvas.width, canvas.height);download(canvas.toDataURL('image/jpeg'));// 下载图片function download (src) {if (!src) return;const a = document.createElement('a');a.setAttribute('download', new Date());a.href = src;a.click();}
关闭摄像头设备
let stream = await navigator.mediaDevices.getUserMedia({audio: true, video: videoConstraints });// 3s后关闭摄像头setTimeout(function () {stream.getTracks().forEach(track => track.stop());stream = null;}, 3000);