js 呼叫本地攝像頭透過canvas進行截圖

如何透過js呼叫本地攝像頭呢?獲取後如何對影片進行截圖呢?在這裡跟大家做一個簡易的Demo來實現以上幾個功能。

涉及到的知識點

navigator.getUserMedia

可以透過該函式來開啟攝像頭獲得流資料

canvas.drawImage

可以透過該函式來將影片的某幀畫到canvas畫布上

canvas.toDataURL

可以透過該函式將canvas畫布生成圖片url

實現的功能點

開啟攝像頭

暫停攝像頭

對影片進行截圖

html簡單佈局

以下先透過HTML我們來實現一個簡單的佈局,包括樣式和按鈕。

<!DOCTYPE html> H5 canvas 呼叫攝像頭進行繪製

您的瀏覽器不支援H5 ,請更換或升級! 截圖 暫停 開啟

樣子差不多是這樣的:

js 呼叫本地攝像頭透過canvas進行截圖

hahiahia 空白一片

我們將

video

進行了隱藏,然後加上了幾個按鈕,還有canvas以及最底部的圖片展示區域(用來存放截圖圖片)。

js實現功能

這裡先貼下核心程式碼:

navigator。getUserMedia({ video : {width:500,height:300}},function(stream){ LV。video。srcObject = stream; LV。video。onloadedmetadata = 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 = ‘js 呼叫本地攝像頭透過canvas進行截圖’ } }; 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 = 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();

原諒我放蕩不羈的命名

。。。

具體已經實現的demo可以點選 https://chrunlee。cn/demos/canvas-video/index。html