摄像头调用主要使用了navigator.getUserMedia()函数。为了将摄像头的画像实时展现,可以将录像数据流导入到video或者canvas中。在展示的时候,建议使用video作为视频流容易,因为canvas绘画视频帧时存在一定的卡顿。
在像素数据分析和将画像转成图片,则应将视频流导到canvas中,使用canvas API中进行数据提取。

在这里,我使用了一个隐藏起来的canvas,对视频流的关键帧数据进行收集。

详看以下代码:

组件代码:

/**
 * 组件:调用摄像头拍摄的构造函数
 * @params {Object} options 参数如下:
 *         video  {DOM} video元素
 *         width  {Number} 画布宽度
 *         height  {Number} 画布高度
 *         onShoot  {Function} 录像回调函数
 *         onError  {Function} error回调函数
 * 调用:
 *     Camera.create(options);
 */
function Camera(options) {
    this.video = options.video;
    this.width = options.width || 640;
    this.height = options.height || 480;
    this.onError = options.onError;
    this.onShoot = options.onShoot;
}

Camera.prototype = {
    init: function() {
        navigator.getUserMedia = navigator.getUserMedia ||
            navigator.webkitGetUserMedia ||
            navigator.mozGetUserMedia ||
            navigator.msGetUserMedia;//获取媒体对象
        window.requestAnimFrame = (function(){
          return  window.requestAnimationFrame       ||
                  window.webkitRequestAnimationFrame ||
                  window.mozRequestAnimationFrame    ||
                  function( callback ){
                    window.setTimeout(callback, 1000 / 60);
                  };
        })();
        this.video.autoplay = 'ture';
        this.canvasDom = document.createElement('canvas');
        this.canvasDom.width = this.width;
        this.canvasDom.height = this.height;
        this.canvasDom.style.display = 'none';
        document.querySelector('body').appendChild(this.canvasDom);
    },

    // 检查摄像头是否可用
    canCameraUse: function() {
        return (navigator.getUserMedia && window.URL);
    },

    // 获取录像流到video中
    shoot: function() {
        var self = this;
        var video = self.video;
        if(self.canCameraUse) {
            navigator.getUserMedia(
                {video:true},
                function (stream) {
                    video.src = URL.createObjectURL(stream);
                    video.play();
                    video.addEventListener('error', function(error) {
                        stream.stop();
                        self.onError && self.onError(error);
                    }, false);
                },
                function (error) {
                    self.onError && self.onError(error);
                }
            );
        }
    },

    // 将录像绘制到canvas
    drawVideo: function() {
        var canvasDom = this.canvasDom;
        var ctx = canvasDom.getContext('2d');
        ctx.fillStyle = "#000000";
        ctx.fillRect(0, 0, canvasDom.width, canvasDom.height);
        ctx.drawImage(this.video, 0, 0, canvasDom.width, canvasDom.height);
    },

    // 录像事件绑定
    addShootEvent: function() {
        var self = this;
        var video = self.video;
        // 正在录像
        video.addEventListener('play', function() {
            function animation() {
                self.drawVideo();
                self.onShoot && self.onShoot();
                window.requestAnimationFrame(animation);
            }
        }, false);
    },

    // 将录像成图片
    snapshot: function(cb, imageType) {
        var self = this;
        var video = self.video;
        var canvas = self.canvasDom;
        var ctx = canvas.getContext('2d');
        imageType = imageType || 'png';
        imageSrc = canvas.toDataURL('image/' + imageType);
        cb && cb(imageSrc);
    },

    // 开始录像
    play: function() {
        this.video.play();
    },

    // 停止录像
    pause: function() {
        this.video.pause();
    },

    render: function() {
        this.init();
        this.shoot();
        this.drawVideo();
        this.addShootEvent();
    }
};

Camera.create = function(options) {
    var camera = new Camera(options);
    camera.render();
    return camera;
};

调用:

<!-- HTML -->
<video id='video'></video>
<div>
    <button id='shootBtn'>拍照</button>
</div>
<div id='imageBox'></div>


<!-- JS -->
<script>
    var camera = Camera.create({
        video: document.querySelector('#video'),
        width: 640,
        height: 480,
        onError: function(error) {
            alert(error);
        }
    });

    // 拍照
    document.querySelector('#shootBtn').addEventListener('click', function() {
        camera.snapshot(function(imageUrl) {
            var imageBox = document.querySelector('#imageBox');
            var image = imageBox.querySelector('img');
            if(!image) {
                var image = document.createElement('img');
                image.src = imageUrl;
                document.querySelector('#imageBox').appendChild(image);
            } else {
                image.src = imageUrl;
            }
        });
    }, false);
</script>

效果如下:

本文作者:子匠_Zijor,转载请注明出处:http://www.dengzhr.com/frontend/html/1335