本地连接两个摄像头拍摄量具,需要切换摄像头进行拍照生成图片,并且把图片传输给后台。
通过navigator对象 MediaDevices.enumerateDevices() 方法 请求一个可用的媒体输入和输出设备的列表,例如麦克风,摄像机,耳机设备等。 返回的 Promise 完成时,会带有一个描述设备的 MediaDeviceInfo 的数组。
MediaDevices 的方法详细描述
实现点击切换摄像头,并且生成图片,传输给后台
<template>
<div class="camera_outer">
<video ref="video" id="videoCamera" :width="videoWidth" :height="videoHeight" autoplay></video>
<canvas style="display:none;" id="canvasCamera" :width="videoWidth" :height="videoHeight"></canvas>
<div v-if="imgSrc" class="img_bg_camera">
<img :src="imgSrc" alt="" class="tx_img">
</div>
<button @click="open()">打开摄像头</button>
<button @click="stopNavigator()">关闭摄像头</button>
<button @click="setImage()">拍照</button>
<button @click="change()">切换摄像头</button>
</div>
</template>
mounted() {
this.thisCancas = document.getElementById('canvasCamera')
this.thisContext = this.thisCancas.getContext('2d')
this.thisVideo = document.getElementById('videoCamera')
var videoElement = document.getElementById('video');
var videoElement1 = document.getElementById('video1');
navigator.mediaDevices.enumerateDevices().then(this.gotDevices)
.catch(this.handleError);
},
methods: {
// 获取本地设备
gotDevices(deviceInfos) {
var constraints = new Array(2);
var id = 0;
for (var i = 0; i !== deviceInfos.length; ++i) {
var deviceInfo = deviceInfos[i];
if (deviceInfo.kind === 'videoinput') {
constraints[id] = {
video: {
deviceId: deviceInfo.deviceId
}
};
id = id + 1;
}
}
this.cameraList = constraints;
},
//打开摄像头
open() {
this._openvideohandler(this.cameraList[0]);
this.flag = true;
},
// 关闭摄像头
close() {
this.detect1Show = false;
this.closeVideo();
this.flag = false;
},
// 切换摄像头
change() {
this.changeFlag = !this.changeFlag;
if (this.changeFlag) {
this._openvideohandler(this.cameraList[1]);
} else {
this._openvideohandler(this.cameraList[0]);
}
},
// 拍照
takePic() {
this.contextmenuhandler();
},
// 生成blob 并且传输给后台
contextmenuhandler() {
this.context2d.drawImage(this.video, 0, 0, 1600, 1200);
this.dataURL64 = this.canvas.toDataURL("image/jpeg");
this.url = this.dataURL64;
// 讲图片生成blob格式
let _this = this;
let data = {
labelId: this.labelId,
taskId: this.$route.params.taskId,
}
this.canvas.toBlob(function (blob) {
_this.blob = blob;
let param = new FormData();
param.append("file", blob);
detectionLabel(data, param).then((res) => {
if (res.data.success) {
_this.$Message.success('检测成功');
_this.detect1Show = false;
_this.closeVideo();
_this.$nextTick(() => {
_this.update();
_this.url = '';
});
} else {
_this.$Message.warning(res.data.msg || '检测失败')
_this.detect1Show = false;
_this.closeVideo();
_this.url = '';
}
})
}, "image/jpeg");
},
}
由于之前做过单摄像头的项目,还算简单的解决这个问题了。在此记录下方法,希望能帮助到有需要的人。