赞
踩
<script setup> import { onMounted, reactive, ref } from 'vue' const videoConstraints = reactive({ width: 500, height: 300 }); let picArr = reactive([]) let videoNode = ref(null) let show = ref(true) let stream = reactive({}) onMounted(async () => { // 获取视频流,并用 video 标签播放 videoNode.value = document.querySelector('#video'); stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: videoConstraints }); videoNode.value.srcObject = stream; videoNode.value.play(); }) // 拍照 const photo = () => { // 通过canvas捕捉video流,生成base64格式图片 const canvas = document.createElement('canvas'); const context = canvas.getContext('2d'); canvas.width = 500; canvas.height = 300; context.drawImage(videoNode.value, 0, 0, canvas.width, canvas.height); // download(canvas.toDataURL('image/jpeg')); picArr.push(canvas.toDataURL('image/jpeg')) // 下载图片 // function download(src) { // if (!src) return; // const a = document.createElement('a'); // a.setAttribute('download', new Date()); // a.href = src; // a.click(); // } } // 切换镜头 const switchs = async () => { show.value = !show.value // enumerateDevices获取所有媒体设备 const mediaDevices = await navigator.mediaDevices.enumerateDevices(); // 通过设备实例king属性videoinput,过滤获取摄像头设备 const videoDevices = mediaDevices.filter(item => item.kind === 'videoinput') || []; console.log(mediaDevices, videoDevices, 'videoDevices') if (show.value) { // 获取前置摄像头 const videoDeviceId = videoDevices[0].deviceId; videoConstraints.deviceId = { exact: videoDeviceId } stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: videoConstraints }); } else { // 获取后置摄像头 if (videoDevices[1]) { const videoDeviceId = videoDevices[1].deviceId; videoConstraints.deviceId = { exact: videoDeviceId } stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: videoConstraints }); } } videoNode.value.srcObject = stream; videoNode.value.play(); } const close = async () => { stream.getTracks().forEach(track => track.stop()); stream = null; } </script> <template> <video id="video" autoplay playsinline muted></video> <button @click="photo">拍照</button> <button @click="switchs">{{show?'切换至后镜头':'切换至前镜头'}}</button> <button @click="close">关闭摄像头设备 </button> <br /> <img v-for="(pic,index) in picArr" :src="pic" :key="index" alt="" /> </template> <style scoped> img { width: 500px; } </style>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。