一个简单的调用摄像头的模块

一个简单的调用摄像头的模块

示例demo

要想调用系统摄像头有以下注意事项:

/**
 * Created by wyc on 2017.2.24
 */
(function () {//摄像头的js
    var conf = {};
    var webCam = {};

// Normalizes window.URL
    window.URL = window.URL || window.webkitURL || window.msURL || window.oURL;

    var promisifiedOldGUM = function (constraints) {

        // First get ahold of getUserMedia, if present
        var getUserMedia = (navigator.getUserMedia ||
        navigator.webkitGetUserMedia ||
        navigator.mozGetUserMedia);

        // Some browsers just don't implement it - return a rejected promise with an error
        // to keep a consistent interface
        if (!getUserMedia) {
            return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
        }

        // Otherwise, wrap the call to the old navigator.getUserMedia with a Promise
        return new Promise(function (resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject);
        });

    }

// Older browsers might not implement mediaDevices at all, so we set an empty object first
    if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
    }

// Some browsers partially implement mediaDevices. We can't just assign an object
// with getUserMedia as it would overwrite existing properties.
// Here, we will just add the getUserMedia property if it's missing.
    if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = promisifiedOldGUM;
    }
    var constraints = {audio: true, video: true};

    /*@param
     {
     el:dom元素(和id二选一)
     id:dom元素的id(和el二选一)
     autoPlay:是否自动播放,默认为true
     }
     */
    function init(param) {
        if (!navigator.mediaDevices.getUserMedia) {
            console.log("浏览器不支持navigator.mediaDevices.getUserMedia");
            return false;
        }
        var conf = {};
        var autoPlay = param.autoPlay === undefined ? true : param.autoPlay;
        conf.ele = param.el || document.getElementById(param.id);
        conf.video = document.createElement("video");
        conf.ele.appendChild(conf.video);
        conf.video.style.width = "100%";
        conf.canvas = document.createElement("canvas");
        var video = conf.video;
        var canvas = conf.canvas;
        var localVideoStream = null;
        function successsCallback(stream) {
            conf.video.addEventListener("loadeddata", function () {
                conf.scale = conf.scale || Math.min(conf.ele.clientHeight / conf.video.clientHeight, conf.ele.clientWidth / conf.video.clientWidth);
                conf.height = conf.video.clientHeight * conf.scale;
                conf.width = conf.video.clientWidth * conf.scale;
                conf.canvas.setAttribute("height", conf.height);
                conf.canvas.setAttribute("width", conf.width);
                conf.video.style.cssText = ' height:100%; transform:scale(' + conf.scale + ')';
                if (param.success && typeof param.success === "function") {
                    param.success();
                }
            });
            conf.video.onloadedmetadata = function (e) {
                if (autoPlay) {
                    conf.video.play();
                }
            };
            conf.video.src = (window.URL && window.URL.createObjectURL) ? window.URL.createObjectURL(stream) : stream;
            localVideoStream = stream;
        }

        function errorCallback(err) {
            console.log(err);
            if (param.error && typeof param.error === 'function') {
                param.error();
            }
        }

        function accessLocalWebCam() {
            navigator.mediaDevices.getUserMedia(constraints)
                .then(function (stream) {
                    successsCallback(stream);
                })
                .catch(function (err) {
                    errorCallback(err);
                });
        }

        function catpureWebCam() {
            if (!conf.canvas) return false;
            var w = conf.width;
            var h = conf.height;
            var context = conf.canvas.getContext("2d");
            var video = conf.video;
            context.drawImage(video, 0, 0, w, h);
            var imageData = context.getImageData(0, 0, w, h);
            return imageData;
        }

        /*
        *拍照,返回一个图片的file
        * callback,拍照后的回调函数入参为file
        * compress 压缩比例默认没有,则返回png图片,compress取值为[0,1],返回为jpg的压缩图片
        * 是否启用flash给用户一种卡顿反馈。默认启用
        * */
        function photo(callback,compress,noFlash) {
            catpureWebCam();
            if(!noFlash){
                flash();
            }
            if(compress&&typeof compress==="number"){
                canvas.toBlob(function (blob) {
                    if (callback) {
                        callback(blob);
                    }
                },"image/jpeg", compress);
            }else{
                canvas.toBlob(function (blob) {
                    if (callback) {
                        callback(blob);
                    }
                });
            }

        }

        function pauseCatpureWebCam() {
            video.pause();
        }

        function stopCatpureWebCam() {
            video.pause();
            if (localVideoStream) {
                var track = localVideoStream.getVideoTracks();
                track[0].stop();
            }
        }

        function startCatpureWebCam() {
            accessLocalWebCam();
        }

        function resumeCatpureWebCam() {
            video.play();
        }

        function flash(time) {
            pauseCatpureWebCam();
            setTimeout(function () {
                resumeCatpureWebCam();
            }, time || 500);
        }

        accessLocalWebCam(conf);
        conf.getImgData = catpureWebCam;
        conf.pause = pauseCatpureWebCam;
        conf.resume = resumeCatpureWebCam;
        conf.stop = stopCatpureWebCam;
        conf.start = startCatpureWebCam;
        conf.flash = flash;
        conf.photo = photo;
        return conf;
    }
    webCam.init = init;
    window.webCam = webCam;
})(window);

使用方法:

var camera = webCam.init({el: cameraBox});
var camera1 = webCam.init({id: "cameraBox1"});


本文标题:一个简单的调用摄像头的模块
本文链接:https://56way.com/p/95.html
作者授权:除特别说明外,本文由 无路 原创编译并授权 小无路 刊载发布。
版权声明:本文不使用任何协议授权,您可以任何形式自由转载或使用。

发表评论

必填

选填

选填

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。