el-upload captures the first frame of the video as the upload cover image

Without further ado, let’s get straight to the code:

/**
 * 获取视频第一帧作为回显封面
 * @param file 至少应包含url信息,即 {url: ""}
 */
export const getVideoCover = (file) => {
  // const  video = document.getElementById("myvideo"); // 获取视频对象
  const video = document.createElement("video"); // 也可以自己创建video
  video.src = file.url; // url地址 url跟 视频流是一样的

  // var canvas = document.getElementById('mycanvas') // 获取 canvas 对象
  var canvas = document.createElement("canvas"); // 获取 canvas 对象
  const ctx = canvas.getContext("2d"); // 绘制2d
  video.crossOrigin = "anonymous"; // 解决跨域问题,也就是提示污染资源无法转换视频
  video.currentTime = 1; // 第一帧

  video.oncanplay = () => {
    canvas.width = video.clientWidth ? video.clientWidth : 320; // 获取视频宽度
    canvas.height = video.clientHeight ? video.clientHeight : 320; //获取视频高度
    // 利用canvas对象方法绘图
    ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
    // 转换成base64形式
    let videoFirstimgsrc = canvas.toDataURL("image/png"); // 截取后的视频封面
    let videoUrl = file.url;
    file.url = videoFirstimgsrc; // file的url储存封面图片
    file.videoUrl = videoUrl; // file的videoUrl储存视频

    video.remove();
    canvas.remove();
  };
  return file;
};

This part is the key code. You can directly copy the entire code and introduce it as a method. It should be noted that it needs to be called after the file is uploaded successfully, preferably in on-success or on-change , otherwise the file will not be obtained.

 In addition, if you want to make a pop-up window where you can view the video by clicking on it, remember to pass the videoUrl of the returned file object into the pop-up window, because the url at this time has been assigned as an image by us.

Guess you like

Origin blog.csdn.net/m0_56683897/article/details/132400960