Skip to content Skip to sidebar Skip to footer

Get An Image From The Video

I want to grab an image from a video based on the current time of the video upon button click. I'm currently using the video tag to play the video but have not seen any resource fo

Solution 1:

This can be done via canvas. Let's say you have a video

<videoid="video"controls="controls">
  ....
</video>

You can do the following:

const video = document.getElementById("video");

const canvas = document.createElement("canvas");
// scale the canvas accordingly
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
// draw the video at that frame
canvas.getContext('2d')
  .drawImage(video, 0, 0, canvas.width, canvas.height);
// convert it to a usable data URLconst dataURL = canvas.toDataURL();

You can then do whatever you want with dataURL, such as displaying it as an image:

var img = document.createElement("img");
img.src = dataURL;

Inspiration drawn from odetocode

Solution 2:

Pure JS way with scale support:

/**
 * Takes a screenshot from video.
 * @param videoEl {Element} Video element
 * @param scale {Number} Screenshot scale (default = 1)
 * @returns {Element} Screenshot image element
 */functiongetScreenshot(videoEl, scale) {
    scale = scale || 1;

    const canvas = document.createElement("canvas");
    canvas.width = videoEl.clientWidth * scale;
    canvas.height = videoEl.clientHeight * scale;
    canvas.getContext('2d').drawImage(videoEl, 0, 0, canvas.width, canvas.height);

    const image = newImage()
    image.src = canvas.toDataURL();
    return image;
}

Post a Comment for "Get An Image From The Video"