您好,登錄后才能下訂單哦!
這篇文章主要介紹了js實現web調用攝像頭的方法,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
具體內容如下
Html
<p> <button onclick="openMedia()">打開</button> <button onclick="closeMedia()">關閉</button> <button onclick="drawMedia()">截取</button> </p> <video id="video" class="bg"></video> <canvas id="qr-canvas"></canvas>
Javascript
<script type="text/javascript"> var video = document.querySelector('video'); var text = document.getElementById('text'); var canvas1 = document.getElementById('qr-canvas'); var context1 = canvas1.getContext('2d'); var mediaStreamTrack; // 一堆兼容代碼 window.URL = (window.URL || window.webkitURL || window.mozURL || window.msURL); if (navigator.mediaDevices === undefined) { navigator.mediaDevices = {}; } if (navigator.mediaDevices.getUserMedia === undefined) { navigator.mediaDevices.getUserMedia = function(constraints) { var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; if (!getUserMedia) { return Promise.reject(new Error('getUserMedia is not implemented in this browser')); } return new Promise(function(resolve, reject) { getUserMedia.call(navigator, constraints, resolve, reject); }); } } //攝像頭調用配置 var mediaOpts = { audio: false, video: true, video: { facingMode: "environment"} // 或者 "user" // video: { width: 1280, height: 720 } // video: { facingMode: { exact: "environment" } }// 或者 "user" } // 回調 function successFunc(stream) { mediaStreamTrack = stream; video = document.querySelector('video'); if ("srcObject" in video) { video.srcObject = stream } else { video.src = window.URL && window.URL.createObjectURL(stream) || stream } video.play(); } function errorFunc(err) { alert(err.name); } // 正式啟動攝像頭 function openMedia(){ navigator.mediaDevices.getUserMedia(mediaOpts).then(successFunc).catch(errorFunc); } //關閉攝像頭 function closeMedia(){ mediaStreamTrack.getVideoTracks().forEach(function (track) { track.stop(); context1.clearRect(0, 0,context1.width, context1.height);//清除畫布 }); } //截取視頻 function drawMedia(){ canvas1.setAttribute("width", video.videoWidth); canvas1.setAttribute("height", video.videoHeight); context1.drawImage(video, 0, 0, video.videoWidth, video.videoHeight); } </script>
感謝你能夠認真閱讀完這篇文章,希望小編分享的“js實現web調用攝像頭的方法”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。