<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta charset="utf-8" /> <title>摄像头</title> </head> <body> <button id="scan">打开摄像头</button> <hr /> <video id="video" muted autoplay></video> </body> </html>
video { width: 100%; height: 50vh; }
const Scan = { videoInputDevice: [], videoElement: document.getElementById("video"), // 获取到的媒体设备 gotDevices(deviceInfos) { let that = this; for (let i = 0; i !== deviceInfos.length; ++i) { let deviceInfo = deviceInfos[i]; if (deviceInfo.kind === 'audioinput') { // 音频设备 } else if (deviceInfo.kind === 'videoinput') { // 视频设备 that.videoInputDevice.push(deviceInfo); } else { // 其他设备 console.log('Found one other kind of source/device: ', deviceInfo); } } }, getStream() { let that = this; if (window.stream) { window.stream.getTracks().forEach((track) => { track.stop(); }); } let constraints = { // 包含audio 可声明音频设备调用 // 声明视频设备调用 // video: true video: { deviceId: { // [1].deviceId 表示后置摄像头,默认开启的是前置摄像头 exact: that.videoInputDevice[1].deviceId } } }; // 视频设备初始化 navigator.mediaDevices.getUserMedia(constraints).then(that.gotStream.bind(that)).catch(that.handleError.bind(that)); that.captureToCanvas(); that.decode(); }, handleError(error) { console.log('Error: ', error); }, gotStream(stream) { let that = this; window.stream = stream; // make stream available to console that.videoElement.srcObject = stream; }, init() { let that = this; // API参考 // https://developer.mozilla.org/zh-CN/docs/Web/API/MediaDevices/enumerateDevices // 先获取设备列表,方便调用后置摄像头 let devices = navigator.mediaDevices.enumerateDevices().then(that.gotDevices.bind(that)); document.querySelector('#scan').addEventListener('click', () => { devices.then(that.getStream.bind(that)).catch(that.handleError.bind(that)); }); } }; Scan.init();