Get image from video javascript; In this tutorial, you will learn how to get/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.
This tutorial will show you how to get image from video. So; create a one html file and play a video using video tag. After that, create a js script to get/capture an image from video.
Get/Capture image from video javascript
Follow the following steps and capture 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.