在Vue中实现截取视频第一帧作为视频封面可以通过以下步骤:

  1. 在Vue组件中引入video.js和videojs-contrib-hls插件。
import videojs from 'video.js';
import 'videojs-contrib-hls';
  1. 在Vue组件中声明一个video元素,并给其添加id。
<video id="my-video"></video>
  1. 在Vue组件中初始化video.js插件,并监听loadedmetadata事件。
mounted() {
  let options = {
    autoplay: false,
    controls: false,
    muted: true,
    preload: 'metadata'
  };

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

  this.player.on('loadedmetadata', () => {
    this.captureVideoThumbnail();
  });
},
  1. 编写captureVideoThumbnail方法来截取视频第一帧。
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. 在Vue组件中使用v-bind指令将videoThumbnail绑定到img元素的src属性上。
<img :src="videoThumbnail" />

完整示例代码如下:

<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>
GitHub 加速计划 / vu / vue
207.54 K
33.66 K
下载
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:2 个月前 )
73486cb5 * chore: fix link broken Signed-off-by: snoppy <michaleli@foxmail.com> * Update packages/template-compiler/README.md [skip ci] --------- Signed-off-by: snoppy <michaleli@foxmail.com> Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 4 个月前
e428d891 Updated Browser Compatibility reference. The previous currently returns HTTP 404. 5 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐