Vue implements intercepting the first frame of the video as the cover

The following steps can be taken to capture the first frame of the video as the video cover in Vue:

  1. Introduce video.js and videojs-contrib-hls plugins in Vue components.
import videojs from 'video.js';
import 'videojs-contrib-hls';
  1. Declare a video element in the Vue component and add an id to it.
<video id="my-video"></video>
  1. Initialize the video.js plugin in the Vue component and listen to the loadedmetadata event.
mounted() {
  let options = {
    autoplay: false,
    controls: false,
    muted: true,
    preload: 'metadata'
  };

  this.player = videojs('my-video', options);

  this.player.on('loadedmetadata', () => {
    this.captureVideoThumbnail();
  });
},
  1. Write the captureVideoThumbnail method to capture the first frame of the video.
captureVideoThumbnail() {
  // 获取第一帧所在的时间戳,单位为秒
  let timestamp = this.player.seekable().end(0) < 5 ? 0 : 5;

  // 将视频移动到第一帧所在的位置
  this.player.currentTime(timestamp);

  // 将当前视频画面绘制到canvas上
  let canvas = document.createElement('canvas');
  canvas.width = this.player.videoWidth();
  canvas.height = this.player.videoHeight();
  canvas.getContext('2d').drawImage(this.player.el(), 0, 0, canvas.width, canvas.height);

  // 将canvas转换为base64格式的图片
  let thumbnail = canvas.toDataURL();

  // 将图片存储到Vue数据中
  this.videoThumbnail = thumbnail;
},
  1. Use the v-bind directive in the Vue component to bind videoThumbnail to the src attribute of the img element.
<img :src="videoThumbnail" />

The complete sample code is as follows:

<template>
  <div>
    <video id="my-video"></video>
    <img :src="videoThumbnail" />
  </div>
</template>

<script>
import videojs from 'video.js';
import 'videojs-contrib-hls';

export default {
  data() {
    return {
      player: null,
      videoThumbnail: null
    }
  },
  mounted() {
    let options = {
      autoplay: false,
      controls: false,
      muted: true,
      preload: 'metadata'
    };

    this.player = videojs('my-video', options);

    this.player.on('loadedmetadata', () => {
      this.captureVideoThumbnail();
    });
  },
  methods: {
    captureVideoThumbnail() {
      let timestamp = this.player.seekable().end(0) < 5 ? 0 : 5;

      this.player.currentTime(timestamp);

      let canvas = document.createElement('canvas');
      canvas.width = this.player.videoWidth();
      canvas.height = this.player.videoHeight();
      canvas.getContext('2d').drawImage(this.player.el(), 0, 0, canvas.width, canvas.height);

      let thumbnail = canvas.toDataURL();

      this.videoThumbnail = thumbnail;
    }
  }
}
</script>

Guess you like

Origin blog.csdn.net/qq_43314341/article/details/130711468