您好,登錄后才能下訂單哦!
這篇文章主要介紹了js實現(xiàn)web調(diào)用攝像頭的方法,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
具體內(nèi)容如下
Html
<p> <button onclick="openMedia()">打開</button> <button onclick="closeMedia()">關(guān)閉</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); }); } } //攝像頭調(diào)用配置 var mediaOpts = { audio: false, video: true, video: { facingMode: "environment"} // 或者 "user" // video: { width: 1280, height: 720 } // video: { facingMode: { exact: "environment" } }// 或者 "user" } // 回調(diào) 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); } //關(guān)閉攝像頭 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實現(xiàn)web調(diào)用攝像頭的方法”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學習!
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。