In this tutorial we will draw a playing video frame as an image inside HTML5 Canvas. Canvas provides a method drawImage
which draws from any source inside a Canvas.
Table of Contents
Define the Video Block
Lets define a video block first inside your HTML code. And put a video source URL for the demo.
Define the Canvas
Now define a canvas beside the Video where the video frame would be shown.
Now put up a link which would trigger the activity of drawing the image from the video.
Pause and Capture image frame from video
Draw the Video Frame
We will use JavaScript to capture and draw the video. Lets define a variable to get our defined Video tag.
var v=document.getElementById("myvideo");
Now add an eventListener
of the link that we created to trigger the event.
pause_lnk.addEventListener('click', pause_and_capture, false);
Once the link is clicked, we will perform below activities in order:
a) Pause the video when link is clicked
HTML5 Video tag provides pause()
event which pause the Video.
v.pause(); // Pause the video to capture
b) Get a handle to the target Canvas
var c = document.getElementById("mycanvas"); // Get the canvas
var ctx = c.getContext("2d");
c) Capture and draw the frame
Canvas provides a drawImage function which takes input the Video tag handle for the source to draw the frame from the video. You can put this piece of code inside a timer to play the Video live in the Canvas. Other two arguments are the co-ordinates in the Canvas where to draw the frame.
ctx.drawImage(v,1,1); // Draw the paused frame of the video to canvas
Demo
Now, putting this all together, I have prepared a demo to show how it works.
Entire Code:
Draw video on HTML5 Canvas - Demo
Play the video and click below link: