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>
相关推荐
烛阴2 分钟前
快速上手Axios:前端开发者必备技能
前端·javascript
摇摇奶昔x10 分钟前
Vue.js 中 “require is not defined“
前端·javascript·vue.js
烛阴20 分钟前
Cheerio DOM操作深度指南:轻松玩转HTML元素操作
前端·javascript·后端
rookie fish34 分钟前
如何控制electron的应用在指定的分屏上打开[特殊字符]
前端·javascript·electron
hweiyu0034 分钟前
Electron简介(附电子书学习资料)
前端·javascript·electron
sunbyte1 小时前
50天50个小项目 (Vue3 + Tailwindcss V4) ✨ | RandomChoicePicker(标签生成)
前端·javascript·vue.js
Everbrilliant891 小时前
音视频之H.264的句法和语义
音视频·h.264·h.264句法和语义·h.264句法表·h.264 nal层语义·h.264序列参数集语义·h.264图像参数集语义
ONLYOFFICE1 小时前
ONLYOFFICE协作空间API指南:使用JavaScript SDK为每个用户结构化协作房间
javascript·编辑器·onlyoffice·office·文档编辑与协作
硬件学长森哥1 小时前
Android音视频多媒体开源框架基础大全
android·图像处理·音视频
开开心心就好1 小时前
高效账号信息管理工具,可安全随机生成密码
javascript·安全·docker·智能手机·pdf·word·excel