0

I'm trying to generate a thumbnail image from a video file. This is my code:

let canvas: HTMLCanvasElement = document.createElement('canvas');
let video: HTMLVideoElement = document.createElement('video');
video.src = video_url;
video.currentTime = 4;

video.onloadedmetadata = () => {
   canvas.width = video.videoWidth;
   canvas.height = video.videoHeight;

   video.currentTime = 4;
};

video.onloadeddata = () => {
    video.currentTime = 4;
    canvas.getContext('2d').drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
    canvas.toBlob(thumbnailBlob => { grabThumbnail(thumbnailBlob) }, 'image/png');
};

It creates the image, but just a blank image. Doesn't get the video frame from the currentTime property. What am I doing wrong?

Roland Rácz
  • 2,879
  • 3
  • 18
  • 44
marvin ralph
  • 1,100
  • 3
  • 23
  • 43
  • 1
    The answer in this possible duplicate of [**Capture frames from video with HTML5 and JavaScript**](https://stackoverflow.com/questions/19175174/capture-frames-from-video-with-html5-and-javascript) explains why that is and what event to use to capture the image. – Nope Jan 12 '18 at 10:37

1 Answers1

1

the property set on line video.currentTime=4 is async in nature and will not give the frame image immediately. You must add event listener for the event seeked. In this event listener method you can generate the thumbnail of the frame at that time.

Let me know if it works.

Gurdev Singh
  • 1,996
  • 13
  • 11