vue 调用电脑的所有摄像头,并随意切换拍照

23 篇文章 1 订阅
5 篇文章 0 订阅

一、问题描述

电脑上安装了三个摄像头,两个前置的摄像头和一个高拍仪拍摄介绍信的,现在需要通过代码来调用摄像头,并区分当前应该调用哪个摄像头完成相应的功能。人脸拍摄调用前置摄像头,拍摄比对好后,应该调用高拍仪拍摄介绍信

样机展示

二、调用代码

<template>
    <div>
        <button @click="callCamera" style="margin-right: 10px;">开启摄像头</button>
        <button @click = 'changeDevice' style="margin-right: 10px;">切换摄像头</button>
        <button @click="closeCamera">关闭摄像头</button>
        <canvas ref="canvas" width="640" height="480"></canvas>
        <video ref="video" width="640" height="480" autoplay></video>
        <button  type="primary" @click="uploadImg">拍照</button>
        <div style="width:200px">
            <div v-for="(item,index) in videoArr" @click="setCurrentDevice(item.id)">{{ item.label }}</div>
        </div>
    </div>
</template>
<script>
    export default {
        data () {
            return {
                videoArr:[],//所有的摄像头,也可以加入音频设备
                modelSel:'',//当前使用的摄像头
                myInterval: null,
            }
        },
        created(){
            this.changeDevice();
        },
        methods: {
            callCamera () {
                navigator.mediaDevices.getUserMedia({
                    video: true
                }).then(success => {
                    this.$refs['video'].srcObject = success;
                    this.$refs['video'].play()
                }).catch(error => {
                    console.error('摄像头开启失败,请检查摄像头是否可用!')
                })
            },
            uploadImg () {
                let ctx = this.$refs['canvas'].getContext('2d');
                ctx.drawImage(this.$refs['video'], 0, 0, 640, 480);
                let imgBase64 = this.$refs['canvas'].toDataURL('image/jpeg', 0.7);
                let str = imgBase64.replace('data:image/jpeg;base64,', '');
                let strLength = str.length;
                let fileLength = parseInt(strLength - (strLength / 8) * 2);
                let size = (fileLength / 1024).toFixed(2);
                console.log(size);
                let ADOM = document.createElement('a');
                ADOM.href = this.headImgSrc
                ADOM.download = new Date().getTime() + '.jpeg';
                ADOM.click()
            },
            closeCamera () {
                if (!this.$refs['video'].srcObject) return;
                let stream = this.$refs['video'].srcObject;
                let tracks = stream.getTracks();
                tracks.forEach(track => {
                    track.stop();
                });
                this.$refs['video'].srcObject = null;
            },
            changeDevice(){
                navigator.mediaDevices.enumerateDevices().then((devices)=> {
                    this.videoArr = [];
                    devices.forEach((device)=> {
                        //音频是audioautput  摄像头videoinput
                        if(device.kind == 'videoinput'){
                            this.videoArr.push({
                                'label': device.label,
                                'id': device.deviceId
                            })
                        }
                    });
                }).catch(function(err) {
                    layer.msg(err.name + ": " + err.message);
                });
            },
            setCurrentDevice(val){
                const videoConstraints = {};
                if (val === '') {
                    videoConstraints.facingMode = 'environment';
                } else {
                    videoConstraints.deviceId = { exact: val };
                }
                var constraints = {
                    video: videoConstraints,
                };
                this.getUserMedia(constraints);
            },
            getUserMedia(constraints, success, error) {
                if (navigator.mediaDevices.getUserMedia) {
                    //最新的标准API
                    navigator.mediaDevices.getUserMedia(constraints).then(success=>{
                        // 摄像头开启成功
                        this.$refs['video'].srcObject = success
                        // 实时拍照效果
                        this.$refs['video'].play()
                    }).catch(error);

                } else if (navigator.webkitGetUserMedia) {
                    //webkit核心浏览器
                    navigator.webkitGetUserMedia(constraints,success, error)
                } else if (navigator.mozGetUserMedia) {
                    //firfox浏览器
                    navigator.mozGetUserMedia(constraints, success, error);
                } else if (navigator.getUserMedia) {
                    //旧版API
                    navigator.getUserMedia(constraints, success, error);
                }
            }
        }
    }
</script>

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值