js如何調用電腦的攝像頭

閒來無事,用js寫了一個調用攝像頭的demo,並用canvas顯示保存。這個功能很實用,好比上傳用戶的頭像,即時拍照及時上傳。html

Html:web

  <video width="200px" height="150px"></video>
    <canvas width="200px" height="150px"></canvas>
    <p>
        <button id="start">打開攝像頭</button>
        <button id="snap">截取圖像</button>
        <button id="close">關閉攝像頭</button>
    </p>

JavaScript:canvas

 window.onload = function () {
            var canvas = document.getElementsByTagName('canvas')[0],
                context = canvas.getContext('2d'),
                video = document.getElementsByTagName("video")[0],
                snap = document.getElementById("snap"),
                close = document.getElementById("close"),
                start = document.getElementById("start"),
                MediaStreamTrack;
            start.addEventListener('click', function () {
                if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                    navigator.mediaDevices.getUserMedia({
                        video: true,
                        audio: true
                    }).then(function (stream) {
                        console.log(stream);
                        MediaStreamTrack=typeof stream.stop==='function'?stream:stream.getTracks()[1];
                        video.src=(window.URL).createObjectURL(stream);
                        video.play();
                    }).catch(function(err){
                        console.log(err);
                    });
                }else if(navigator.getMedia){
                    navigator.getMedia({
                        video: true
                    }).then(function (stream) {
                        console.log(stream);
                        MediaStreamTrack=stream.getTracks()[1];
                        video.src=(window.webkitURL).createObjectURL(stream);
                        video.play();
                    }).catch(function(err){
                        console.log(err);
                    });
                }
            });
            snap.addEventListener('click', function () {
                context.drawImage(video, 0, 0,200,150);
            });
            close.addEventListener('click', function () {
                MediaStreamTrack && MediaStreamTrack.stop();
            });
        }

總結:上面這個Demo主要用到瀏覽器的攝像頭組件,而後再將圖片源賦給canvas。其中遇到一個坑:代碼須要託管到服務器端,即在客戶端訪問才能調用瀏覽器成功。這種禁止本地調用的作法多是出於瀏覽器的安全性和用戶的隱私考慮。瀏覽器

相關文章
相關標籤/搜索