<video id="video" :width="videoWidth" :height="videoHeight" autoplay></video>
<canvas id="canvas" :width="videoWidth" :height="videoHeight"></canvas>
<button plain onclick="getCompetence" :disabled="disabled">打开摄像头</button>
<button plain onclick="setImage" :disabled="!disabled">拍照</el-button>
<button plain onclick="stopNavigator" :disabled="!disabled">关闭摄像头</button>
调用权限(打开摄像头功能),video标签播放摄像头
async getCompetence() {
let videoStream = null;
this.thisCancas = document.getElementById("canvas");
//建立一个2d对象
this.thisContext = this.thisCancas.getContext("2d");
this.thisVideo = document.getElementById("video");
定义摄像头窗口等参数
var constraints = { audio: false, video: { width: this.videoWidth, height: this.videoHeight, transform: "scaleX(-1)" } };
if ("mediaDevices" in navigator && "getUserMedia" in navigator.mediaDevices) {
//上传参数
videoStream = await navigator.mediaDevices.getUserMedia(constraints);
//显示video窗口
this.thisVideo.style.display = "inline";
//src
this.thisVideo.srcObject = videoStream;
this.thisVideo.play();
//按钮是否可点击
this.disabled = true;
}
}
绘制图片(拍照功能)
async setImage() {
// 点击,canvas画图,drawImage方法画图
this.thisContext.drawImage(this.thisVideo, 0, 0, this.videoWidth, this.videoHeight);
// 获取图片base64链接
var image = this.thisCancas.toDataURL("image/png");
this.imgSrc = image;
let uint8 = this.getUint8Arr(image);
let filename = new Date() + ".png";
let file = new File([uint8.u8arr], filename, { type: uint8.mime });
//也可以下载拍照图片
// let url = URL.createObjectURL(file);
// const a = document.createElement("a");
// a.setAttribute("href", url);
// a.setAttribute("download", file.name);
// a.click();
// URL.revokeObjectURL(url);
let fileData = new FileRequst();
fileData.fileName = file.name;
fileData.data = file;
//这一步是调接口上传文件
this.model.picUri = await this.uploadClient.uploadImage(fileData);
}
getUint8Arr(dataurl: any) {
// 截取base64的数据内容
let arr = dataurl.split(","),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
// 获取解码后的二进制数据的长度,用于后面创建二进制数据容器
n = bstr.length,
// 创建一个Uint8Array类型的数组以存放二进制数据
u8arr = new Uint8Array(n);
// 将二进制数据存入Uint8Array类型的数组中
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return { u8arr, mime };
}
关闭摄像头
stopNavigator() {
//停止播放
this.thisVideo.srcObject.getTracks()[0].stop();
//关闭时隐藏video标签,否则黑色
this.thisVideo.style.display = "none";
//按钮是否可点击
this.disabled = false;
}