能够使用浏览器打开手机端摄像头
生活随笔
收集整理的這篇文章主要介紹了
能够使用浏览器打开手机端摄像头
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
能夠前后攝像頭切換,能夠截取當前視頻流圖像
兼容各大主流瀏覽器,
主要使用的api:
// 獲取視頻流 navigator.mediaDevices.getUserMedia(constrains).then(success).catch(error);// 獲取設備攝像信息 navigator.mediaDevices.enumerateDevices().then(gotDevices).then(getStream).catch(handleError);之前在本機上測試Chrome出現問題,問題在于沒有使用https作為測試鏈接,如果使用http的話,則項目不能打開攝像頭,這可能與chrome的明文加密有關系
如果使用http,代碼會報
NotSupportedError Only secure origins are allowed (see: https://goo.gl/Y0ZkNV)
但是這個錯開始并沒有報,開始我直接運行獲取視頻流代碼,項目的代碼仿佛停止運行一般,相應位置的console.log也沒有輸出,這個錯誤也沒有報
后來經過調試,獲取視頻流的代碼放在點擊事件中,錯誤才出來。。
切換攝像頭代碼:
// 多選框更改事件 videoSelect.onchange = getStream;// 獲取設備音頻輸出設備與攝像設備,這里我只用到了攝像設備 function gotDevices(deviceInfos) {console.log('deviceInfos')console.log('deviceInfos:', deviceInfos);for (let i = 0; i !== deviceInfos.length; i++) {let deviceInfo = deviceInfos[i];var option = document.createElement('option');// console.log(deviceInfo)if (deviceInfo.kind === 'videoinput') { // audiooutput , videoinputoption.value = deviceInfo.deviceId;option.text = deviceInfo.label || 'camera ' + (videoSelect.length + 1);videoSelect.appendChild(option);}} }兼容瀏覽器:
//訪問用戶媒體設備的兼容方法 function getUserMedia(constrains,success,error){if(navigator.mediaDevices.getUserMedia){//最新標準APInavigator.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){//舊版APInavigator.getUserMedia(constrains).then(success).catch(error);} }獲取視頻流成功回調:
function getStream(){if (window.stream) {window.stream.getTracks().forEach(function(track) {track.stop();})}if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia){//調用用戶媒體設備,訪問攝像頭const constraints = {audio: true, video: {width: { ideal: 1280 },height: { ideal: 720 },frameRate: { ideal: 10,max: 15},deviceId: {exact: videoSelect.value}}};console.log('獲取視頻流');getUserMedia(constraints,success,error);} else {alert("你的瀏覽器不支持訪問用戶媒體設備");} }截取視頻流作為圖片:
//注冊拍照按鈕的單擊事件 document.getElementById("capture").addEventListener("click",function(){//繪制畫面console.log('點擊事件');context.drawImage(video,0,0,480,320); });源碼地址
總結
以上是生活随笔為你收集整理的能够使用浏览器打开手机端摄像头的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: AOP****
- 下一篇: Css3位移动画效果