vue项目中利用后端接口返回的视频地址获取第一帧作为数据封面展示

1:利用转成base64进行获取封面

javascript 复制代码
//封装函数 
 getVideoBase64(url) {
            return new Promise(function (resolve, reject) {
                let dataURL = "";
                let video = document.createElement("video");
                video.setAttribute("crossOrigin", "anonymous"); //处理跨域
                video.setAttribute("src", url);
                video.setAttribute("width", 400);
                video.setAttribute("height", 240);
                video.setAttribute("preload", "auto");
                video.setAttribute('crossOrigin', 'anonymous');
                video.addEventListener("loadeddata", function () {
                    let canvas = document.createElement("canvas"),
                        width = video.width, //canvas的尺寸和图片一样
                        height = video.height;
                    canvas.width = width;
                    canvas.height = height;
                    canvas.getContext("2d").drawImage(video, 0, 0, width, height); //绘制canvas
                    dataURL = canvas.toDataURL("image/jpeg"); //转换为base64
                    resolve(dataURL);
                });
            })
        },




//使用该函数
       if (res.data.data.clipList) {  //数据
          setTimeout(() => {
            //item.videoUrl  视频地址    item.coverUrl  图片地址
            res.data.data.clipList.forEach((item, index) => {
              this.getVideoBase64(item.videoUrl).then((data) => {
                item.coverUrl = data
              });
            });
          }, 1000);
        }

2:利用canvas来获取视频第一帧作为封面

javascript 复制代码
    //转换第一帧
    cutPicture(item) {
      let video = document.createElement("video");
      video.style = 'position:fixed; top: 9999px;left:9999px;z-index:-9999'
      video.preload = 'metadata'
      video.currentTime = 1   //截取的视频第一秒作为图片
      video.src = item.videoUrl
      video.setAttribute('crossOrigin', 'anonymous');
      video.width = 113
      video.height = 75
      document.body.appendChild(video)
      video.onloadeddata = function () {
        let canvas = document.createElement('canvas')
        canvas.width = 113
        canvas.height = 75
        canvas.getContext('2d').drawImage(video, 0, 0, video.clientWidth, video.clientHeight)
        var oGrayImg = canvas.toDataURL('image/jpeg');
        item.videoUrl = oGrayImg
        this.remove()
      }
      return item
    },
相关推荐
不会敲代码113 分钟前
TCP/IP 与前端性能:从数据包到首次渲染的底层逻辑
前端·tcp/ip
kyriewen24 分钟前
奥特曼借GPT-5.5干杯,而你的Copilot正按Token收钱
前端·github·openai
AC赳赳老秦28 分钟前
投标合规提效:用 OpenClaw 实现标书 / 合同自动审核、关键词校验、格式优化,降低废标风险
开发语言·前端·python·eclipse·emacs·deepseek·openclaw
kyriewen35 分钟前
代码写成一锅粥?3个设计模式让你的项目“起死回生”
前端·javascript·设计模式
千寻girling1 小时前
《 Git 详细教程 》
前端·后端·面试
之歆2 小时前
DAY08_CSS浮动与行内块布局实战指南(下)
前端·css
yqcoder3 小时前
CSS Position 全解析:5 种定位模式详解
前端·css
Rhi6373 小时前
从零搭建项目:React 19 + Vite 8 + Tailwind CSS v4 实战配置
前端
竹林8183 小时前
用Viem替代ethers.js:从一次签名失败到完整迁移的实战记录
前端·javascript
之歆3 小时前
DAY08_CSS浮动与行内块布局实战指南(上)
前端·css