< 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 ( ) => {
videoNode. value = document. querySelector ( '#video' ) ;
stream = await navigator. mediaDevices. getUserMedia ( {
audio : true ,
video : videoConstraints
} ) ;
videoNode. value. srcObject = stream;
videoNode. value. play ( ) ;
} )
const photo = ( ) => {
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) ;
picArr. push ( canvas. toDataURL ( 'image/jpeg' ) )
}
const switchs = async ( ) => {
show. value = ! show. value
const mediaDevices = await navigator. mediaDevices. enumerateDevices ( ) ;
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>