Capture Image from Video using Javascript

Get or capture image from video using javascript; Through this tutorial, i am going to show you how to get or capture image from videos using javascript.

Capture Image from Video using Javascript

Use the following steps and capture or get image from video using javascript:

  • Step 1 – Create Html Markup
  • Step 2 – Create Script to Get Image From Video

Step 1 – Create Html Markup

Create a new HTML file with .html extension and update the following code into your xyz.html file:

<video id="video" src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" type="video/mp4" controls></video>
<button onclick="cap()">Capture</button>
<canvas id="canvas" style="overflow:auto"></canvas>

In the HTML file, you can see the video tag for playing the video on your web browser. And one button for performing the image capture task with the capture function of javascript

Step 2 – Create Script to Get Image From Video

Next step, create a script tag and update the following code script into your file:

function cap() {
var canvas = document.getElementById('canvas');
var video = document.getElementById('video');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext('2d').drawImage(video, 0, 0, video.videoWidth, video.videoHeight); // for drawing the video element on the canvas
 
/** Code to merge image **/
const playImage = new Image();
playImage.src = 'path to image asset';
playImage.onload = () => {
const startX = (video.videoWidth / 2) - (playImage.width / 2);
const startY = (video.videoHeight / 2) - (playImage.height / 2);
canvas.getContext('2d').drawImage(playImage, startX, startY, playImage.width, playImage.height);
canvas.toBlob() = (blob) => { // Canvas element gives a callback to listen to the event after blob is prepared from canvas
const img = new Image();
img.src = window.URL.createObjectUrl(blob); // window object with static function of URL class that can be used to get URL from blob
};
};
}

Here, drawing the current instance using drawImage() of the video with the canvas tag and then fetching the blog as for the image.

Conclusion

In this Javascript GET Image from Video example, you have learned how to capture image from video using Javascript.

More JavaScript Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published.