当前位置:网站首页>通过canvas获取视频第一帧封面图

通过canvas获取视频第一帧封面图

2020-11-08 23:46:00 action

let video = document.createElement('video');
video.style="width:0;height:0;position:fixed;right:-100%;"
video.muted = 'muted';
video.autoplay = 'autoplay';
video.onloadeddata = function() {
  let { width, height } = getVideoSize(120, this.videoWidth, this.videoHeight);
  let canvas = document.createElement('canvas');
  canvas.width = width;
  canvas.height = height;
  canvas.getContext('2d').drawImage(this, 0, 0, width, height);
  // 视频转换为图片
  canvas.toDataURL('image/png')
  document.body.removeChild(video);
}
video.src = URL.createObjectURL(file.files[0]); // file本地文件
document.body.appendChild(video);

// 获取视频等比缩放宽高
function getVideoSize(maxWidth, width, height) {
  if(maxWidth >= width) {
    return {
      width,
      height
    }
  } else {
    return {
      width: maxWidth,
      height: Math.floor(maxWidth / width * height)
    }
  }
}

版权声明
本文为[action]所创,转载请带上原文链接,感谢
https://segmentfault.com/a/1190000037765094