今天来了一个需求,说是实现拍照的功能,我左思又想,我就把下面代码想了出来
style="width: 300px; height: 200px;" @click="naImage(src)"/>
import { uploadImg } from "@/api/interface";
export default {
name: "Camera",
data() {
return {
// imgSrc: "", // 默认值为空s
imgSrc:[],
os: false, //控制摄像头开关
thisVideo: null,
thisContext: null,
thisCancas: null,
videoWidth: 300,
videoHeight: 200,
};
},
created() {},
mounted(){
//这个是页面已加载就会触发这个方法
this.getCompetence();
},
methods: {
// 调用摄像头权限
getCompetence() {
this.$nextTick(() => {
const _this = this;
this.os = false;
this.thisCancas = document.getElementById("canvasCamera");
this.thisContext = this.thisCancas.getContext("2d");
this.thisVideo = document.getElementById("videoCamera");
if (navigator.mediaDevices === undefined) {
navigator.menavigatordiaDevices = {};
}
if (navigator.mediaDevices.getUserMedia === undefined) {
navigator.mediaDevices.getUserMedia = function (constraints) {
let getUserMedia =
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.getUserMedia;
if (!getUserMedia) {
return Promise.reject(
new Error("getUserMedia is not implemented in this browser")
);
}
return new Promise(function (resolve, reject) {
getUserMedia.call(navigator, constraints, resolve, reject);
});
};
}
const constraints = {
audio: false,
video: {
width: _this.videoWidth,
height: _this.videoHeight,
transform: "scaleX(-1)",
},
};
navigator.mediaDevices
.getUserMedia(constraints)
.then(function (stream) {
if ("srcObject" in _this.thisVideo) {
_this.thisVideo.srcObject = stream;
} else {
_this.thisVideo.src = window.URL.createObjectURL(stream);
}
_this.thisVideo.onloadedmetadata = function (e) {
_this.thisVideo.play();
};
})
.catch((err) => {
this.$notify({
title: "警告",
message: "没有开启摄像头权限或浏览器版本不兼容.",
type: "warning",
});
});
});
},
//绘制图片
async drawImage() {
this.thisContext.drawImage(
this.thisVideo,
0,
0,
this.videoWidth,
this.videoHeight
);
// 获取图片base64链接
//this.imgSrc = this.thisCancas.toDataURL("image/png");
const newImgSrc = this.thisCancas.toDataURL("image/png");
this.imgSrc.push(newImgSrc);
},
naImage(src){
console.log("图片的地址",src);
//把这个图片转换成base64
let arr = src.split(",");
let array = arr[0].match(/:(.*?);/);
let mime = (array && array.length > 1 ? array[1] : type) || type;
// 去掉url的头,并转化为byte
let bytes = window.atob(arr[1]);
// 处理异常,将ascii码小于0的转换为大于0
let ab = new ArrayBuffer(bytes.length);
// 生成视图(直接针对内存):8位无符号整数,长度1个字节
let ia = new Uint8Array(ab);
for (let i = 0; i < bytes.length; i++) {
ia[i] = bytes.charCodeAt(i);
}
const randomNumber = Math.floor(1000 + Math.random() * 9000);
const fileNameJPG = `图片${randomNumber}.jpg`;
let formData = new FormData();
formData.append(
"file",
new File([ia], fileNameJPG, { type: mime })
);
//上传图片接口
uploadImg(formData).then((res) => {
console.log(res.filePaths,'哈哈哈');
});
},
},
};
以上代码你拿过来就可以直接用,这个是完整的代码,喜欢的支持以下把