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

一、问题描述

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

样机展示

二、调用代码

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

Vue.js应用中集成WebRTC做视频聊天时,切换摄像头通常是通过JavaScript API来实现的。以下是基本步骤: 1. 首先,在HTML中添加用于显示视频流的`<video>`元素,设置它作为本地媒体流的目标: ```html <template> <div id="video-container"> <video ref="localVideo" id="local-video"></video> </div> </template> <script> export default { methods: { toggleCamera() { // 实现切换摄像头的部分 } }, mounted() { this.getUserMedia(); }, async getUserMedia() { const stream = await navigator.mediaDevices.getUserMedia({ video: true }); this.localStream = stream; this.updateLocalVideo(stream); }, updateLocalVideo(stream) { this.$refs.localVideo.srcObject = stream; } } </script> ``` 2. 在`toggleCamera`方法中,利用`navigator.mediaDevices.enumerateDevices()`获取可用的摄像头设备,然后选择另一个设备替换当前的本地流: ```javascript methods: { toggleCamera() { navigator.mediaDevices.enumerateDevices() .then(devices => { if (devices.length > 1) { // 检查是否有备用摄像头 const currentDeviceId = this.localStream.getTracks()[0].id; // 获取当前摄像头设备ID devices.forEach(device => { if (device.kind === 'videoinput' && device.id !== currentDeviceId) { this.switchToNewDevice(device); } }); } else { console.log('No secondary camera found.'); } }) .catch(error => console.error('Error enumerating devices:', error)); }, async switchToNewDevice(device) { try { const newStream = await navigator.mediaDevices.getUserMedia({ video: { deviceId: device.deviceId } }); this.localStream.getTracks().forEach(track => track.stop()); // 关闭旧摄像头 this.localStream = newStream; // 更新本地流 this.updateLocalVideo(newStream); } catch (error) { console.error('Failed to switch cameras:', error); } } } ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值