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>
相关推荐
GDAL28 分钟前
HTML 中的 Canvas 样式设置全解
javascript
Macdo_cn34 分钟前
My Metronome for Mac v1.4.2 我的节拍器 支持M、Intel芯片
macos·音视频
GDAL40 分钟前
HTML Canvas clip 深入全面讲解
前端·javascript·canvas
GISer_Jing1 小时前
Javascript排序算法(冒泡排序、快速排序、选择排序、堆排序、插入排序、希尔排序)详解
javascript·算法·排序算法
JustHappy1 小时前
「我们一起做组件库🌻」做个面包屑🥖,Vue的依赖注入实战💉(VersakitUI开发实录)
前端·javascript·github
拉不动的猪1 小时前
刷刷题16
前端·javascript·面试
kiramario1 小时前
【结束】JS如何不通过input的onInputFileChange使用本地mp4文件并播放,nextjs下放入public文件的视频用video标签无法打开
开发语言·javascript·音视频
化作繁星3 小时前
如何在 React 中测试高阶组件?
前端·javascript·react.js
Au_ust3 小时前
千峰React:函数组件使用(2)
前端·javascript·react.js
余~~185381628003 小时前
矩阵碰一碰发视频的后端源码技术,支持OEM
线性代数·矩阵·音视频