当前位置:网站首页>Get the first cover image of video through canvas

Get the first cover image of video through 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);
  //  Video to picture 
  canvas.toDataURL('image/png')
  document.body.removeChild(video);
}
video.src = URL.createObjectURL(file.files[0]); // file Local files 
document.body.appendChild(video);

//  Get the video with equal scale width and height 
function getVideoSize(maxWidth, width, height) {
  if(maxWidth >= width) {
    return {
      width,
      height
    }
  } else {
    return {
      width: maxWidth,
      height: Math.floor(maxWidth / width * height)
    }
  }
}

版权声明
本文为[action]所创,转载请带上原文链接,感谢