源碼地址:https://github.com/fastCreator/qrcodeScan
css
//訪問用戶媒體設備的兼容方法function getUserMedia(constrains, success) { let error = (err) => { console.error('API:getUserMedia,' + err) } if (navigator.mediaDevices.getUserMedia) { //最新標準API navigator.mediaDevices.getUserMedia(constrains).then(success).catch(error); } else if (navigator.webkitGetUserMedia) { //webkit內核瀏覽器 navigator.webkitGetUserMedia(constrains).then(success).catch(error); } else if (navigator.mozGetUserMedia) { //Firefox瀏覽器 navagator.mozGetUserMedia(constrains).then(success).catch(error); } else if (navigator.getUserMedia) { //舊版API navigator.getUserMedia(constrains).then(success).catch(error); }}
//兼容性獲取視頻流配置項async function getConstraints() { const constraints = { audio: false, video: { width: { max: 400 }, height: { max: 280 } // facingMode: { exact: "environment" } //標準寫法 } }; //獲取設備信息,而且找出攝像頭1,爲後置攝像頭 let devices = await navigator.mediaDevices.enumerateDevices() let videoinput = devices.filter(it => it.kind === 'videoinput') if (videoinput[1]) { constraints.video.deviceId = { exact: videoinput[1].deviceId || videoinput[0].deviceId } } return constraints}