1function getVideoCover(file, seekTo = 0.0) {
2 console.log("getting video cover for file: ", file);
3 return new Promise((resolve, reject) => {
4 // load the file to a video player
5 const videoPlayer = document.createElement('video');
6 videoPlayer.setAttribute('src', URL.createObjectURL(file));
7 videoPlayer.load();
8 videoPlayer.addEventListener('error', (ex) => {
9 reject("error when loading video file", ex);
10 });
11 // load metadata of the video to get video duration and dimensions
12 videoPlayer.addEventListener('loadedmetadata', () => {
13 // seek to user defined timestamp (in seconds) if possible
14 if (videoPlayer.duration < seekTo) {
15 reject("video is too short.");
16 return;
17 }
18 // delay seeking or else 'seeked' event won't fire on Safari
19 setTimeout(() => {
20 videoPlayer.currentTime = seekTo;
21 }, 200);
22 // extract video thumbnail once seeking is complete
23 videoPlayer.addEventListener('seeked', () => {
24 console.log('video is now paused at %ss.', seekTo);
25 // define a canvas to have the same dimension as the video
26 const canvas = document.createElement("canvas");
27 canvas.width = videoPlayer.videoWidth;
28 canvas.height = videoPlayer.videoHeight;
29 // draw the video frame to canvas
30 const ctx = canvas.getContext("2d");
31 ctx.drawImage(videoPlayer, 0, 0, canvas.width, canvas.height);
32 // return the canvas image as a blob
33 ctx.canvas.toBlob(
34 blob => {
35 resolve(blob);
36 },
37 "image/jpeg",
38 0.75 /* quality */
39 );
40 });
41 });
42 });
43}
44