如何通過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 = 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 = 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();原諒我放蕩不羈的命名 …
原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/224052.html
微信掃一掃
支付寶掃一掃