js截取video视频某一帧为图片

1.代码如下

javascript 复制代码
<template>
  <div class="box">
    <div class="video-box">
      <video controls ref="videoRef" preload="true"
        src="https://qt-minio.ictshop.com.cn:9000/resource-management/2025/01/08/7b96ac9d957c45a7a94b355ca7a89d02.mp4"></video>
      <a-button type="primary" @click="saveCoverImg" :loading="loading">{{ loading ? '截取中': '保存为封面' }}</a-button>
    </div>

    <img :src="coverImg" alt="">
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue';

const videoRef = ref(null)
const coverImg = ref(null)
const loading = ref(false)

function saveCoverImg() {
  videoRef.value.pause();
  loading.value = true;
  const currentTime = videoRef.value.currentTime;
  createVideo(currentTime)
}

function createVideo(currentTime) {
  const videoElement = document.createElement("video");
  videoElement.setAttribute("crossorigin", "anonymous"); // 解决跨域问题
  videoElement.currentTime = currentTime
  videoElement.muted = true;
  videoElement.autoplay = true;
  videoElement.oncanplay = function () {
    drawCoverImage(videoElement)
  }
  videoElement.src = "https://qt-minio.ictshop.com.cn:9000/resource-management/2025/01/08/7b96ac9d957c45a7a94b355ca7a89d02.mp4";
}

function drawCoverImage(vEle) {
  const c = document.createElement("canvas");
  const ctx = c.getContext("2d");
  c.width = vEle.videoWidth;
  c.height = vEle.videoHeight;
  ctx.drawImage(vEle, 0, 0, c.width, c.height);
  const img = c.toDataURL("image/png");
  coverImg.value = img;
  loading.value = false;
}

</script>

<style lang="less" scoped>
.box {
  .video-box {
    display: flex;
    align-items: flex-end;

    video {
      width: 490px;
      margin: 10px 10px 0 0;
    }
  }

  img {
    width: 300px;
    margin-top: 10px;
  }
}
</style>
相关推荐
小李子呢021129 分钟前
前端八股Vue(6)---v-if和v-for
前端·javascript·vue.js
程序员buddha31 分钟前
ES6 迭代器与生成器
前端·javascript·es6
aq55356001 小时前
网页开发四剑客:HTML/CSS/JS/PHP全解析
javascript·css·html
程序员buddha1 小时前
TypeScript详细教程
javascript·ubuntu·typescript
CyL_Cly2 小时前
Bilidown下载 1.2.7 bilibili视频下载
音视频
haierccc2 小时前
Win7、2008R2、Win10、Win11使用FLASH的方法
前端·javascript·html
We་ct2 小时前
LeetCode 50. Pow(x, n):从暴力法到快速幂的优化之路
开发语言·前端·javascript·算法·leetcode·typescript·
Hilaku2 小时前
卷AI、卷算法、2026 年的前端工程师到底在卷什么?
前端·javascript·面试
非凡ghost2 小时前
AIMP(音乐播放软件)
前端·windows·音视频·firefox
军军君012 小时前
Three.js基础功能学习十五:智能黑板实现实例二
开发语言·前端·javascript·vue.js·3d·threejs·三维