Capture Image from Video using Javascript

    Jul 15, 2019       by Pankaj Kumar
capture-image-from-video.jpg

While web application development, You may be in need to capture the image of the video. This task can be achieved easily with javascript.

So, Today I am going to show you how we can capture an image from video using javascript. 

 

Have a look on our html code:

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

 

In the above code we can see the video tag for playing the video below that we have a button for performing the image capture task with capture function of javascript.  And then there is a canvas.

 

Javascript function for image capture:

 

 
function capture() {
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 **/
/** For instance, if I want to merge a play image on center of existing 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
};
};
}
 

 

With the above javascript code we are drawing the current instance of the video on the canvas and then retrieving the blog as for the image. For now its just displaying on the window, We can store it over server or AWS or anywhere as per our requirement.

 

Conclusion

So in this article, I explained how to capture image from video using Javascript. Find many Javascript Sample Application demos  and other javascript frameworks to start the app for enterprise level application

Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.

Thanks!

You can download complete code from here. Download Code


WHAT'S NEW

Find other similar Articles here: