<template>
<div class="warp">
<div class="warp_content">
<video ref="video" autoplay style="background-color: #000"></video>
<canvas ref="canvas" style="display: none;"></canvas>
<img ref="image" src="" />
</div>
<button class="warp_but" @click="takePhoto">拍照</button>
</div>
</template>
<script>
export default {
data() {
return {
ctx:null,
cvs:null,
video:null,
}
},
mounted(){
this.init()
},
methods: {
init() {
const that = this
const cvs = that.$refs.canvas
that.cvs = cvs
const video = that.$refs.video
that.video = video
cvs.width = cvs.height = video.width = video.height = 400
const { width, height } = cvs
that.ctx = cvs.getContext('2d')
const constraints = {
video: {
width,
height
}
}
navigator.mediaDevices.getUserMedia(constraints).then(stream => {
video.srcObject = stream
video.onloadedmetadata = () => video.play()
})
},
takePhoto() {
const that = this
const { width, height } = that.cvs
that.ctx.drawImage(that.video, 0, 0, width, height)
that.$refs.image.src = that.cvs.toDataURL('image/png')
}
}
}
</script>
<style></style>
vue项目中调用前置摄像头拍照功能
于 2023-11-13 14:21:08 首次发布