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="" 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.


In this post, you have learned how to capture image from video using Javascript.

Related Posts