如何設置瀏覽器調用攝像頭,怎么讓瀏覽器調用攝像頭

很多網友想了解如何設置瀏覽器調用攝像頭的相關知識,為了大家進一步的對怎么讓瀏覽器調用攝像頭所有了解,就跟小編一起來看看吧!

如何通過js調用本地攝像頭呢?獲取后如何對視頻進行截圖呢?在這里跟大家做一個簡易的Demo來實現以上幾個功能 。
涉及到的知識點
  • navigator.getUserMedia 可以通過該函數來打開攝像頭獲得流數據
  • canvas.drawImage 可以通過該函數來將視頻的某幀畫到canvas畫布上
  • canvas.toDataURL 可以通過該函數將canvas畫布生成圖片url
實現的功能點
  • 打開攝像頭
  • 暫停攝像頭
  • 對視頻進行截圖
html簡單布局
以下先通過HTML我們來實現一個簡單的布局,包括樣式和按鈕 。
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>H5 canvas 調用攝像頭進行繪制</title><style>html,body{width:100%;height:100%;padding: 0px;margin: 0px;overflow: hidden;}#canvas{width:500px;height:300px;}#video{width:500px;height:300px;}.btn{display:inline-block;text-align: center;background-color: #333;color:#eee;font-size:14px;padding:5px 15px;border-radius: 5px;cursor:pointer;}</style> </head> <body><video id="video" autoplay="true" style="background-color:#ccc;display:none;"></video><div style="width:500px;height:300px;margin:30px auto;"><canvas id="canvas" width="500px" height="300px">您的瀏覽器不支持H5 ,請更換或升級!</canvas><span class="btn" filter="screenshot">截圖</span><span class="btn" filter="close">暫停</span><span class="btn" filter="open">打開</span></div><div style="width:500px;height:300px;margin:40px auto;" id="show"></div> </body> </html>樣子差不多是這樣的:
如何設置瀏覽器調用攝像頭,怎么讓瀏覽器調用攝像頭


如何設置瀏覽器調用攝像頭,怎么讓瀏覽器調用攝像頭


hahiahia 空白一片
我們將video進行了隱藏,然后加上了幾個按鈕,還有canvas以及最底部的圖片展示區域(用來存放截圖圖片) 。
js實現功能
【如何設置瀏覽器調用攝像頭,怎么讓瀏覽器調用攝像頭】這里先貼下核心代碼:
navigator.getUserMedia({video : {width:500,height:300} },function(stream){LV.video.srcObject = stream;LV.video.onloadedmetadata = https://juhangye.com/function(e) {LV.video.play();}; },function(err){alert(err);//彈窗報錯 })相關的知識點可以參考:https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia
然后根據頁面邏輯實現事件以及其他功能,包括:截圖、暫停 。
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;var events = {open : function(){LV.open();},close : function(){console.log(LV.timer);clearInterval(LV.timer);},screenshot : function(){//獲得當前幀的圖像并拿到數據var image = canvas.toDataURL('jpeg');document.getElementById('show').innerHTML = '<img src="'+image+'" style="width:500px;height:300px;" />'}};var LV = {video : document.getElementById('video'),canvas : document.getElementById('canvas'),timer : null,media : null,open :function(){if(!LV.timer){navigator.getUserMedia({video : {width:500,height:300}},function(stream){LV.video.srcObject = stream;LV.video.onloadedmetadata = https://juhangye.com/function(e) {LV.video.play();};},function(err){alert(err);//彈窗報錯})}if(LV.timer){clearInterval(LV.timer);}//將畫面繪制到canvas中LV.timer = setInterval(function(){LV.ctx.drawImage(LV.video,0,0,500,300);},15);},init : function(){LV.ctx = LV.canvas.getContext('2d');//綁定事件document.querySelectorAll('[filter]').forEach(function(item){item.onclick = function(ev){var type = this.getAttribute('filter');events[type].call(this,ev);}});return LV;}};LV.init();

推薦閱讀