js如何调用电脑的摄像头

闲来无事,用js写了一个调用摄像头的demo,并用canvas显示保存。这个功能很实用,比如上传用户的头像,即时拍照及时上传。

Html:

  <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:

 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。其中遇到一个坑:代码需要托管到服务器端,即在客户端访问才能调用浏览器成功。这种禁止本地调用的做法可能是出于浏览器的安全性和用户的隐私考虑。

posted @ 2018-04-18 21:18  Jinus  阅读(21396)  评论(1编辑  收藏  举报