Skip to content

Instantly share code, notes, and snippets.

@msichterman
Created November 17, 2023 17:09
Show Gist options
  • Save msichterman/38a43686462f2c8607d288aabb1e8292 to your computer and use it in GitHub Desktop.
Save msichterman/38a43686462f2c8607d288aabb1e8292 to your computer and use it in GitHub Desktop.
Get a video thumbnail dynamically using <canvas>
/**
* Generates thumbnails on demand to show as video previews
* @param videoUrl - the S3 video url
* @returns "blob:" url to the first video frame
*/
const getVideoThumbnail = async (videoUrl: string) => {
return new Promise<string>((resolve, reject) => {
const video = document.createElement("video");
video.crossOrigin = "anonymous";
video.src = videoUrl;
video.autoplay = true;
video.preload = "metadata";
video.muted = true;
video.playsInline = true;
video.play();
video.onloadeddata = async () => {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
if (!ctx) {
reject(new Error("Canvas context is not supported"));
return;
}
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
try {
const blob = await new Promise<Blob>((resolve) =>
canvas.toBlob((blob) => resolve(blob!))
);
const thumbnailObjectURL = URL.createObjectURL(blob);
resolve(thumbnailObjectURL);
} catch (error) {
reject(error);
}
};
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment