Using HTML5 video with canvas

Using HTML5 video with canvas

You’ve already learned a lot about the <video> element in my previous article “What I’ve Learned From Working With HTML5 Video Over A Month”, but did you know that the <video> and <canvas> elements would be a great choice to use together? In fact, the two elements are absolutely wondrous when you combine them! I will show you a handy demo using these two elements, which I hope will prompt cool future projects from you. Firstly, place the <video> and <canvas>elements in your HTML. Give your dimensions(width, height) to <canvas> according to your video. And of course, hide your video with the hidden attribute or “display: none” styling. Because <canvas> will do the trick for you ;) Let’s go through them one by one.


We’re hiding the video element because we just want <canvas> to show the video, not <video> element itself.


Let’s declare the variables that will be used.


Here is the magical part, with the whole code.
drawImage() method draws the video onto the canvas. video.onpause()video.onended(), and video.onplay() methods are related to the performance issue. When the video paused or ended, we do not need to draw <video> onto the<canvas>, because you know, the frame is not changing after paused or ended. And when the <video> starts playing/resuming, <canvas> should start/resume drawing the <video> onto <canvas> as well.