Vue 调用电脑摄像头拍照 返回base64格式图片 简单例子
调用电脑摄像头拍照的简单例子,延伸使用可参考往期帖子 戳我传送
<template>
<div>
<el-button @click="isShow = !isShow">{{
isShow ? "显示" : "隐藏"
}}</el-button>
<el-button @click="OpenCamera" v-show="!isOpen">打开摄像头</el-button>
<el-button @click="CloseCamera" v-show="isOpen">关闭摄像头</el-button>
<el-button @click="setImage" v-show="isOpen">拍照</el-button>
<br />
<video
ref="captureVideo"
id="captureVideo"
:class="isShow ? 'isShow' : ''"
></video>
<canvas id="canvasCamera" :class="isShow ? 'isShow' : ''"></canvas>
<div v-if="imgSrc" :class="isShow ? 'isShow' : ''">
<img :src="imgSrc" class="captureImg" />
</div>
</div>
</template>
<script>
export default {
data() {
return {
imgSrc: "", // 拍照图片
canvas: null,
context: null,
videoWidth: 0, //视频实际宽度
videoHeight: 0, //视频实际高度
isShow: false,
isOpen: false,
};
},
mounted() {
// this.OpenCamera();
},
methods: {
// 调用打开摄像头功能
OpenCamera(flag) {
// console.log("flag", flag);
var me = this;
// 获取 canvas 画布
this.canvas = document.getElementById("canvasCamera");
this.context = this.canvas.getContext("2d");
// 旧版本浏览器可能根本不支持mediaDevices,我们首先设置一个空对象
if (navigator.mediaDevices === undefined) {
navigator.mediaDevices = {};
}
// 正常支持版本
navigator.mediaDevices
.getUserMedia({
video: true,
})
.then((stream) => {
this.isOpen = true;
// 摄像头开启成功
this.$refs.captureVideo.srcObject = stream;
this.$refs.captureVideo.play();
var video = document.querySelector("#captureVideo");
video.addEventListener("canplay", function () {
me.videoWidth = video.videoWidth;
me.videoHeight = video.videoHeight;
video.style.width = me.videoWidth + "px";
video.style.height = me.videoHeight + "px";
var canvas = document.querySelector("canvas");
canvas.width = me.videoWidth;
canvas.height = me.videoHeight;
});
})
.catch((err) => {
console.log(err);
});
},
// 关闭摄像头
CloseCamera() {
console.log("关闭摄像头");
this.$refs.captureVideo.srcObject.getTracks()[0].stop();
this.isOpen = false;
this.imgSrc = null;
this.context.clearRect(0, 0, this.videoWidth, this.videoHeight);
},
// 拍照 绘制图片
setImage(type) {
console.log("拍照");
// 点击canvas画图
this.context.drawImage(
this.$refs.captureVideo,
0,
0,
this.videoWidth,
this.videoHeight
);
// 获取图片base64链接
const image = this.canvas.toDataURL("image/png");
this.imgSrc = image;
// 干点啥呢
},
},
};
</script>
<style lang="scss" scoped>
#captureVideo {
width: 100px;
// display: none;
}
#canvasCamera {
// display: none;
}
.captureImg {
// display: none;
width: 300px;
height: auto;
}
.isShow {
display: none;
}
</style>
原文地址:https://blog.csdn.net/Jokerxiuka/article/details/142873405
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!