Html5中的 video標籤 無法關閉攝像頭
阿新 • • 發佈:2019-02-18
html5中的video這個標籤是引入視訊的,通過navigator.getUserMedia去獲取攝像頭的視訊流,
所以在事件裡用關閉的程式碼都不能執行關閉攝像頭,只有關閉網頁,攝像頭才關閉。
需求:不關閉網頁,實現攝像頭關閉
暫時的解決辦法:
beforeRouteLeave (to, from, next) {
this.$router.go(-1); //重新整理路由
}
第二種解決辦法:
this.mediaStreamTrack && this.mediaStreamTrack.stop();
呼叫攝像頭,拍照程式碼:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style> #canvas,#video { float: left; margin-right: 10px; background: #fff; } .box { overflow: hidden; margin-bottom: 10px; } </style> </head> <body> <!--video用於顯示媒體裝置的視訊流,自動播放--> <video id="video" controls="controls" autoplay style="width: 480px;height: 320px"></video> <!--拍照按鈕--> <div> <button id="capture">拍照</button> <button id="guanbi">拍照</button> </div> <!--描繪video截圖--> <canvas id="canvas" width="480" height="320"></canvas> <script> //訪問使用者媒體裝置的相容方法 function getUserMedia(constrains,success,error){ //debugger if(navigator.mediaDevices.getUserMedia){ //最新標準API navigator.mediaDevices.getUserMedia(constrains).then(success); } else if (navigator.webkitGetUserMedia){ //webkit核心瀏覽器 navigator.webkitGetUserMedia(constrains).then(success); } else if (navigator.mozGetUserMedia){ //Firefox瀏覽器 navagator.mozGetUserMedia(constrains).then(success); } else if (navigator.getUserMedia){ //舊版API navigator.getUserMedia(constrains).then(success); } } var video = document.getElementById("video"); var canvas = document.getElementById("canvas"); var context = canvas.getContext("2d"); //成功的回撥函式 function success(stream){ //debugger //相容webkit核心瀏覽器 var CompatibleURL = window.URL || window.webkitURL; //將視訊流設定為video元素的源 video.src = CompatibleURL.createObjectURL(stream); //播放視訊 video.play(); } //異常的回撥函式 function error(error){ //debugger console.log("訪問使用者媒體裝置失敗:",error.name,error.message); } if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia){ //呼叫使用者媒體裝置,訪問攝像頭 //debugger getUserMedia({ video:{width:480,height:320} },success,error); } else { alert("你的瀏覽器不支援訪問使用者媒體裝置"); } //註冊拍照按鈕的單擊事件 document.getElementById("capture").addEventListener("click",function(){ //繪製畫面 context.drawImage(video,0,0,480,320); }); //註冊關閉按鈕的單擊事件 document.getElementById("guanbi").addEventListener("click",function(){ debugger //實測無法關閉 }); </script> </body> </html>
參考來源: