Javascript: Capture Image from Video

Javascript: Capture Image from Video

In this tutorial, you will learn how to capture image from videos using javascript.

Sometimes, you develop web applications in any programming language with javascript, You may be in need to capture the image of the video.

In this post, we will create a one html file and play a video using video tag. After that, create a js script to capture an image from video.

Capture image from video javascript

Follow the following steps and capture image from video using javascript:

1: Html Code

First of all, 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

2 : Script tag

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 post, you have learned how to capture image from video using Javascript.

AuthorTuts Make

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Javascript, JQuery, Laravel, Codeigniter, Vue JS, Angular JS, React Js, WordPress and Bootstrap from a starting stage.

Leave a Reply

Your email address will not be published. Required fields are marked *