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
    },
相关推荐
tERS ERTS1 分钟前
头歌答案--爬虫实战
java·前端·爬虫
当时只道寻常8 分钟前
Vue3 集成 NProgress 进度条:从入门到精通
前端·vue.js
kyriewen9 分钟前
React性能优化:从“卡成狗”到“丝般顺滑”的5个秘诀
前端·react.js·性能优化
米丘9 分钟前
Vue 3.x 单文件组件(SFC)模板编译过程解析
前端·vue.js·编译原理
helloweilei12 分钟前
Web Streams 简介
前端·javascript
悟空瞎说12 分钟前
Flutter热更新 Shorebird CodePush 原理、实现细节及费用说明
前端·flutter
didadida26212 分钟前
从“不存在”的重复请求,聊到 Web 存储的深坑
前端
xiaominlaopodaren14 分钟前
Three.js 渲染原理-透明渲染为什么这么难
前端
米丘15 分钟前
vue3.x 内置指令有哪些?
前端·vue.js