js html调用摄像头拍照

2 篇文章 0 订阅

最近了一个windows10的项目,需要调用后置摄像头进行图片操作,然后在网上参考也是遇到了一些坑,总结一下。

先看界面

涉及的主要代码如下(我的业务逻辑就不写了,使用的时候结合你自己业务逻辑替换对应的就可以了):

//获取设备

window.navigator.getUserMedia = navigator.getUserMedia || navigator.webKitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
            navigator.mediaDevices.enumerateDevices().then(function(mediaDeviceInfos) {
                //console.log(mediaDeviceInfos)
                mediaDeviceInfos.forEach(function(item, index) {
                    if(item.kind === 'videoinput') {
                        _this.exArray.push(item.deviceId)    //存储源设备
                    }
                })
            })

 

//点击拍照

openMedia: function() {
                var _this = this;
                const videoConstraints = {};
                videoConstraints.deviceId = {
                    exact: _this.exArray.length > 1 ? _this.exArray[1] : _this.exArray[0]   //两个摄像头 1是后置摄像头 0是前置摄像头
                };
                if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {

                    navigator.mediaDevices.getUserMedia({
                            'audio': false,
                            'video': videoConstraints
                        })
                        .then(function(mediaStream) {
                            _this.getVideoStream(mediaStream)
                        })
                        .catch(function(error) {
                            alert(error.name + "--" + error.message)
                            alert(error)
                            console.log(error)
                        })
                } else if(navigator.getUserMedia) {
                    mui.toast("111")
                    navigator.getUserMedia({
                        'video': true,
                        'audio': false
                    }, _this.getVideoStream, _this.getFail)
                } else {
                    alert('不支持摄像头调用!')
                }
            },

//调用成功
            getVideoStream: function(stream) {
                var _this = this;
                console.log(111);
                _this.buffer = stream;
                _this.mediaStreamTrack = typeof stream.stop === 'function' ? stream : stream.getTracks()[1];
                if(_this.video.mozSrcObject !== undefined) {
                    _this.video.mozSrcObject = _this.buffer;
                } else {
                    _this.video.srcObject = stream // window.URL && window.URL.createObjectURL(_this.buffer) 注释掉的这个已经要被弃用;
                }
                //oCapture.play();
            },
            getFail: function() {

            },

           //关闭设备
            stopMediaTracks: function(stream) {
                stream.getTracks().forEach(track => {
                    track.stop();
                });
            },

          //保存图片
            savePhonto: function() {
                var _this = this;
                _this.isSavePic = true;
                _this.stopMediaTracks(_this.buffer);
                document.getElementById('photo').style.display = 'none';
                document.getElementById('takePhoto').style.display = 'block';
                //关闭摄像头
                _this.mediaStreamTrack && _this.mediaStreamTrack.stop();
                mui('#camera').popover('toggle', document.getElementById("bottom"));
                var _this = this;
                if(_this.pictureType === 'bimprovement') {
                    app.$data.imgs.push({
                        name: _this.dataURLtoFile(_this.convertCanvasToImage(_this.canvas), 'hst' + new Date().getTime()),
                        url: _this.convertCanvasToImage(_this.canvas),
                        isSave: 0
                    })
                    _this.isSavePic = false;
                } else if(_this.pictureType === 'aimprovement') {
                    app.$data.imgs2.push({
                        name: _this.dataURLtoFile(_this.convertCanvasToImage(_this.canvas), 'modhst' + new Date().getTime()),
                        url: _this.convertCanvasToImage(_this.canvas),
                        isSave: 0
                    })
                    _this.isSavePic = false;
                }
                console.log(app.$data.imgs);
            },

         dataURLtoFile: function(dataurl, filename) { //将base64转换为文件
                var arr = dataurl.split(','),
                    mime = arr[0].match(/:(.*?);/)[1],
                    bstr = atob(arr[1]),
                    n = bstr.length,
                    u8arr = new Uint8Array(n);
                while(n--) {
                    u8arr[n] = bstr.charCodeAt(n);
                }
                return new File([u8arr], filename, {
                    type: mime
                });
            },
            convertCanvasToImage: function(canvas) {
                var image = new Image();
                image.src = canvas.toDataURL("image/png");
                //return image;
                return canvas.toDataURL("image/png");
            },

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值