vue h5调用摄像头
<template>
<div>
<video ref="cameraVideo" id="video" preload autoplay loop muted></video>
<button type="primary" @click="openCamera">打开摄像头</button>
<button type="primary" @click="closeCamera">关闭摄像头</button>
<button type="primary" @click="switchCamera">切换摄像头</button>
{{ logInfo }}
</div>
</template>
<script>
export default {
name: "cameraVideo",
props: {
videoWidth: {
type: Number,
default: 300,
},
videoHeight: {
type: Number,
default: 300,
}
},
data() {
return {
videoEle: null,
constraints: {
video: {
deviceId: {
exact: "",
},
width: this.videoWidth,
height: this.videoHeight,
},
audio: false,
},
cameraArray: [],
cameraIndex: 0,
openCameraLock: false,
closeCameraLock: false,
logInfo: ''
};
},
created() {
navigator.mediaDevices.getUserMedia({ video: true }).then((MediaStream) => {
navigator.mediaDevices
.enumerateDevices()
.then((devices) => {
this.logInfo += JSON.stringify(devices)
this.cameraArray = [];
devices.forEach((device) => {
if (device.kind == "videoinput") {
this.cameraArray.push(device.deviceId);
}
});
if (this.cameraArray.length > 0) {
this.constraints.video.deviceId.exact = this.cameraArray[0];
}
this.logInfo += JSON.stringify(this.cameraArray)
this.logInfo += JSON.stringify(this.constraints)
})
.catch(function (err) {
console.log(err.name + ": " + err.message);
this.logInfo += JSON.stringify(err)
});
})
.catch((PermissionDeniedError) => {
this.logInfo += JSON.stringify(PermissionDeniedError)
this.logInfo += 123
});
},
methods: {
openCamera() {
if (this.openCameraLock) {
return;
}
this.openCameraLock = true;
this.closeCamera();
console.log("打开摄像头");
if (this.cameraArray.length <= 0) {
this.$message.warning("没有可用的摄像头");
}
this.videoEle = this.$refs.cameraVideo;
let promise = navigator.mediaDevices.getUserMedia(this.constraints);
promise
.then((MediaStream) => {
this.logInfo += 'promise.then'
this.videoEle.srcObject = MediaStream;
this.videoEle.play();
})
.catch((PermissionDeniedError) => {
this.logInfo += 'promise.catch'
});
this.openCameraLock = false;
console.log("摄像头开启完毕");
},
switchCamera() {
if (
this.cameraArray.length > 0 &&
!this.closeCameraLock &&
!this.openCameraLock
) {
if (
this.constraints.video.deviceId.exact ===
this.cameraArray[this.cameraIndex]
) {
this.cameraIndex++;
if (this.cameraIndex >= this.cameraArray.length) {
this.cameraIndex = 0;
}
}
this.constraints.video.deviceId.exact = this.cameraArray[
this.cameraIndex
];
this.closeCamera();
this.openCamera();
return true;
}
},
closeCamera() {
if (this.videoEle != null && this.videoEle.srcObject != null) {
console.log("关闭摄像头");
this.closeCameraLock = true;
let stream = this.videoEle.srcObject;
let tracks = stream.getTracks();
tracks.forEach((track) => {
track.stop();
});
this.videoEle.pause();
this.videoEle = null;
this.closeCameraLock = false;
console.log("摄像头已关闭");
}
},
},
destroyed() {
this.closeCamera();
},
};
</script>