【js】获取媒体流实现拍照功能,摄像头切换

<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>

在这里插入图片描述

  • 9
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值