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>
相关推荐
颜酱5 小时前
图结构完全解析:从基础概念到遍历实现
javascript·后端·算法
小迷糊的学习记录6 小时前
Vuex 与 pinia
前端·javascript·vue.js
发现一只大呆瓜6 小时前
前端性能优化:图片懒加载的三种手写方案
前端·javascript·面试
不爱吃糖的程序媛6 小时前
Flutter 与 OpenHarmony 通信:Flutter Channel 使用指南
前端·javascript·flutter
利刃大大6 小时前
【Vue】Element-Plus快速入门 && Form && Card && Table && Tree && Dialog && Menu
前端·javascript·vue.js·element-plus
NEXT067 小时前
AI 应用工程化实战:使用 LangChain.js 编排 DeepSeek 复杂工作流
前端·javascript·langchain
光影少年7 小时前
react的hooks防抖和节流是怎样做的
前端·javascript·react.js
小毛驴8507 小时前
Vue 路由示例
前端·javascript·vue.js
发现一只大呆瓜8 小时前
AI流式交互:SSE与WebSocket技术选型
前端·javascript·面试
wuhen_n9 小时前
JavaScript链表与双向链表实现:理解数组与链表的差异
前端·javascript