调用电脑摄像头拍照的简单例子,延伸使用可参考往期帖子 戳我传送
<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 /><videoref="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>