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>
相关推荐
小沐°9 分钟前
vue-设置不同环境的打包和运行
前端·javascript·vue.js
qq_419854051 小时前
CSS动效
前端·javascript·css
南村群童欺我老无力.1 小时前
Flutter应用鸿蒙迁移实战:性能优化与渐进式迁移指南
javascript·flutter·ci/cd·华为·性能优化·typescript·harmonyos
花哥码天下2 小时前
恢复网站console.log的脚本
前端·javascript·vue.js
奔跑的呱呱牛2 小时前
geojson-to-wkt 坐标格式转换
javascript·arcgis
康一夏3 小时前
React面试题,封装useEffect
前端·javascript·react.js
❆VE❆4 小时前
WebSocket与SSE深度对比:技术差异、场景选型及一些疑惑
前端·javascript·网络·websocket·网络协议·sse
ConardLi4 小时前
SFT、RAG 调优效率翻倍!垂直领域大模型评估实战指南
前端·javascript·后端
over6975 小时前
🌟 JavaScript 数组终极指南:从零基础到工程级实战
前端·javascript·前端框架
源猿人5 小时前
前端批量请求的并发控制与工程化实践
javascript