司項目需要調用攝像頭,看了一下html5文檔,主要是使用html5的getUserMedia()API,寫一個例子來記錄具體的使用方法。
<html> <body> <!-- 用于展示攝像頭視頻流 --> <video id="video" autoplay style="width: 480px;height: 320px"></video> <div> <button id="capture" onclick="handleClickCapture()">拍照</button> </div> <!-- 展示拍攝的照片 --> <canvas id="canvas" width="480" height="320"></canvas> <script> var video = document.getElementById('video'); var capture = document.getElementById('capture'); var ctx = document.getElementById('canvas').getContext('2d'); /** * 調用用戶媒體設備 * @param constraints 配置信息 * @param success 成功回調函數 * @param error 失敗回調函數 */ function getUserMediaToPhoto(constraints,success,error) { if(navigator.mediaDevices.getUserMedia){ navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error); }else if (navigator.webkitGetUserMedia) { navigator.webkitGetUserMedia(constraints,success,error); }else if(navigator.mozGetUserMedia){ navigator.mozGetUserMedia(constraints,success,error); }else if(navigator.getUserMedia){ navigator.getUserMedia(constraints,success,error); } } /** * 成功回調函數 * @param stream 視頻流 */ function success(stream){ var CompatibleURL = window.URL || window.webkitURL; try { video.src = CompatibleURL.createObjectURL(stream); } catch (e) { video.srcObject = stream; } video.play(); } /** * 失敗回調 * @param error 錯誤對象 */ function error(error) { console.log('無法訪問媒體設備', error); } if(navigator.mediaDevices.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia){ getUserMediaToPhoto({video:{width:480,height:320}},success,error); }else{ alert('不支持訪問用戶媒體設備'); } /** * 拍照按鈕點擊事件 */ function handleClickCapture() { ctx.drawImage(video,0,0,480,320); } </script> </body> </html>
實現了基本的攝像頭調用和拍照,實現思路非常簡單,基本上只是在調用api,唯一惡心的地方在于api版本比較多,不得不多做一些判斷。具體的api介紹、使用和參數可以查看MediaDevices.getUserMedia()。
何通過js調用本地攝像頭呢?獲取后如何對視頻進行截圖呢?在這里跟大家做一個簡易的Demo來實現以上幾個功能。
以下先通過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以及最底部的圖片展示區域(用來存放截圖圖片)。
這里先貼下核心代碼:
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();
原諒我放蕩不羈的命名 ...
具體已經實現的demo可以點擊 https://chrunlee.cn/demos/canvas-video/index.html
自網絡
這是大家在做信息類網站的時候經常要用到的一個功能:
理想情況下我們應該先判斷你的設備上是否有攝像頭或相機,但簡單起見,我們在這里直接寫出了HTML標記,而不是用JavaScript先判斷然后動態生成這些標記
<video id="video" width="300" height="240" autoplay></video>
<button id="snap">拍照</button>
<canvas id="canvas" width="300" height="240"></canvas>
</body>
</html>
$( function() {
try { document.createElement("canvas").getContext("2d"); } catch (e) { alert("not support canvas!") }
var video = document.getElementById("video"),
canvas = document.getElementById("canvas"),
context = canvas.getContext("2d");
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
if (navigator.getUserMedia)
navigator.getUserMedia(
{ "video": true },
function (stream) {
if (video.mozSrcObject !== undefined)video.mozSrcObject = stream;
else video.src = ((window.URL || window.webkitURL || window.mozURL || window.msURL) && window.URL.createObjectURL(stream)) || stream;
video.play();
},
function (error) {
alert("Video capture error: " + error.code);
}
);
else alert("Native device media streaming (getUserMedia) not supported in this browser");
document.getElementById("snap").addEventListener("click", function() {
/*context.drawImage(video, 0, 0, 640, 480);//照片大小*/
context.drawImage(video, 0, 0, canvas.width = video.videoWidth, canvas.height = video.videoHeight)
}, false);
*請認真填寫需求信息,我們會在24小時內與您取得聯系。