1

我正在尝试开发一个网站,我可以在其中从移动设备中的 chrome 切换相机。当前我使用 vuejs 2 框架并使用 MediaDevices.getUserMedia() 拍摄图像。从这里我明白我将如何使用我的代码。前后摄像头分别工作。但是在我试图在两者之间切换的地方它不起作用。这是我的代码:

<template>
    <div class="container" id="scanIdCardPage">
        <div class="scanIdCardDiv">
                <div class="scanCardContainer" v-show="afterTakingPhoto">
                    <video ref="video" id="video" :style="{width: divWidth}" autoplay></video>
                    <canvas ref="canvas" id="canvas" width="320" height="240" style="display: none;"></canvas>
                </div>
            </div>
        </div>

        <div class="takePhotoBtnDiv">
            <div>
                <button type="button" class="btn btn-info" @click="camera('environment')">Back Camera</button>
                <button type="button" class="btn btn-info" @click="camera('user')">front Camera</button>
            </div>
        </div>
    </div>
</template>

export default {
    data() {
      video: {},
      front: true
    },
    methods: {
        Camera() {
            if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                navigator.mediaDevices.getUserMedia({ video: { facingMode: (this.front? "user" : "environment") }}).then(stream => {
                    this.video.src = window.URL.createObjectURL(stream);
                    this.video.play();
                });
            }
        },
        changeCamera() {
           this.front = !this.front;
        }
    },
    mounted() {
      this.Camera();
    }
}

谁能帮我看看如何更换相机?TIA

4

1 回答 1

3

我得到了我的解决方案。MediaDevices.getUserMedia() 不能直接改变 video facesMode。首先,您必须停止正在运行的视频流。然后改变视频面临模式。这是我的代码:

export default() {
    data() {
    },
    methods: {
        camera(face) {
            this.stop();
            this.gum(face);
        },
        stop() {
            return video.srcObject && video.srcObject.getTracks().map(t => t.stop());
        },
        gum(face) {
            if(face === 'user') {
                return navigator.mediaDevices.getUserMedia({video: {facingMode: face}})
                .then(stream => {
                    video.srcObject = stream;
                    this.localstream = stream;
                });
            }
            if(face === 'environment') {
                return navigator.mediaDevices.getUserMedia({video: {facingMode: {exact: face}}})
                .then(stream => {
                    video.srcObject = stream;
                    this.localstream = stream;
                });
            }
        }
    },
    mounted() {
        this.camera('environment');
    },
}
于 2018-07-01T05:51:02.207 回答