retrieve video thumbnail in javascript

To retrieve a video thumbnail in JavaScript, you can use the HTML5 video element and the HTMLCanvasElement along with the drawImage() method. Here's an example:

index.tsx
// Create a video element
var video = document.createElement('video');
video.src = 'path/to/video.mp4';

// Wait for the video to load metadata
video.addEventListener('loadedmetadata', function() {
  // Set the canvas size to match the video dimensions
  var canvas = document.createElement('canvas');
  canvas.width = video.videoWidth;
  canvas.height = video.videoHeight;

  // Draw the first frame of the video onto the canvas
  var ctx = canvas.getContext('2d');
  ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

  // Retrieve the thumbnail data URL from the canvas
  var thumbnailUrl = canvas.toDataURL();

  // Use the thumbnailUrl as needed (e.g., set it as the source of an image element)
  var thumbnailImage = document.createElement('img');
  thumbnailImage.src = thumbnailUrl;

  // Append the thumbnail image to the document
  document.body.appendChild(thumbnailImage);
});

// Start loading the video
video.load();
938 chars
29 lines

In this example, we create a video element, set its source to the video file, and wait for the metadata to load. Once the metadata is available, we create a canvas element with the same dimensions as the video. Then, we draw the first frame of the video onto the canvas using the drawImage() method. Finally, we retrieve the thumbnail URL from the canvas using the toDataURL() method and use it as needed (e.g., set it as the source of an image element and append it to the document).

Note: The example assumes you have a video file located at 'path/to/video.mp4'. Please replace it with the correct path to your video file.

related categories

gistlibby LogSnag