该示例使用 HTML5 的 MediaDevices 和 MediaRecorder API,以及 canvas 进行视频播放和截图。

<template>
  <div class='recorder'>
    <canvas ref='canvas' width='200' height='200'></canvas>
    <div class='timer'>{{ timer }}s</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      stream: null,
      recorder: null,
      timer: 3,
      intervalId: null,
      backgroundColors: ['#ff0000', '#00ff00', '#0000ff'],
      currentColorIndex: 0,
    };
  },
  methods: {
    async startRecording() {
      this.stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false });
      this.recorder = new MediaRecorder(this.stream);
      this.recorder.ondataavailable = (event) => {
        const blob = event.data;
        const reader = new FileReader();
        reader.onload = () => {
          const base64 = reader.result.split(',')[1];
          // do something with base64
        };
        reader.readAsDataURL(blob);
      };
      this.recorder.start();
      this.intervalId = setInterval(() => {
        this.timer--;
        if (this.timer === 0) {
          this.stopRecording();
        }
      }, 1000);
      this.changeBackgroundColor();
    },
    stopRecording() {
      this.recorder.stop();
      this.stream.getTracks().forEach((track) => track.stop());
      clearInterval(this.intervalId);
      this.timer = 3;
    },
    changeBackgroundColor() {
      this.$el.style.backgroundColor = this.backgroundColors[this.currentColorIndex];
      this.currentColorIndex = (this.currentColorIndex + 1) % this.backgroundColors.length;
      setTimeout(() => this.changeBackgroundColor(), 1000);
    },
  },
  mounted() {
    this.startRecording();
  },
};
</script>

<style scoped>
.recorder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 200px;
  height: 200px;
  border-radius: 50%;
  overflow: hidden;
}
.timer {
  font-size: 24px;
  font-weight: bold;
  margin-top: 10px;
  color: white;
}
</style>

startRecording 方法请求浏览器摄像头,创建 MediaRecorder 对象录制视频。每秒更新计时器,调用 changeBackgroundColor 方法改变背景色。stopRecording 方法停止录制并关闭摄像头。录制完成后将视频转换为 Base64 格式,并进行处理。播放视频部分可以根据需要进行实现。

Vue 自动开启摄像头录制3秒圆形视频并转Base64

原文地址: https://www.cveoy.top/t/topic/oJR0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录