vue实现调用手机拍照、录像功能
warning:
这篇文章距离上次修改已过205天,其中的内容可能已经有所变动。
在Vue中,可以使用HTML5的navigator.mediaDevices.getUserMedia
API来调用手机的摄像头进行拍照或录像。以下是一个简单的例子,展示了如何在Vue组件中实现调用摄像头的功能:
<template>
<div>
<video ref="video" autoplay style="width: 640px; height: 480px;"></video>
<button @click="takePhoto">拍照</button>
<button @click="startRecording">开始录像</button>
<button @click="stopRecording" :disabled="!isRecording">停止录像</button>
<canvas ref="canvas" style="display: none;"></canvas>
</div>
</template>
<script>
export default {
data() {
return {
mediaRecorder: null,
isRecording: false,
recordedBlobs: []
};
},
methods: {
takePhoto() {
const video = this.$refs.video;
const canvas = this.$refs.canvas;
const ctx = canvas.getContext('2d');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
ctx.drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
},
startRecording() {
const video = this.$refs.video;
const stream = video.srcObject;
this.mediaRecorder = new MediaRecorder(stream, { mimeType: 'video/webm' });
this.recordedBlobs = [];
this.isRecording = true;
this.mediaRecorder.ondataavailable = event => {
if (event.data && event.data.size > 0) {
this.recordedBlobs.push(event.data);
}
};
this.mediaRecorder.start();
},
stopRecording() {
this.mediaRecorder.stop();
this.isRecording = false;
},
async getCameraStream() {
const constraints = {
video: { width: 640, height: 480 }
};
try {
const stream = await navigator.mediaDevices.getUserMedia(constraints);
this.$refs.video.srcObject = stream;
} catch (error) {
console.error('Error accessing the camera:', error);
}
}
},
mounted() {
this.getCameraStream();
}
};
</script>
在这个例子中,getCameraStream
方法用于访问用户的摄像头,并将获取到的流设置到一个video
元素上。takePhoto
方法捕获当前视频流中的画面并将其绘制到canvas
上,实现拍照功能。startRecording
和 stopRecording
方法分别用于开始和停止视频录制,录制的内容可以保存为Blob文件。
评论已关闭