Using HTML5 Video with Canvas

Photo by Alina Grubnyak on Unsplash

View

<canvas width="1280" height="720"></canvas>
<video
src="foo.mp4"
preload="auto"
autoplay
playsinline
webkit-playsinline
muted
hidden
>
</video>

Declarations

Let’s declare the variables that will be used.

const canvas = document.querySelector('canvas');
const video = document.querySelector('video');
const fps = 60;
const width = 1280;
const height = 720;
const canvasInterval = null;
  1. First, let’s get our <canvas> and <video> elements to use later.
  2. fps means frame per second. It’s important according to the video’s frame. You may want to use it as 24, or 30, or 60. It will be used for the interval’s millisecond value.
  3. width and height are the dimensions in pixels of the video. They will be given to the canvas element. If you do not specify them, <canvas> will take 300 for width and 150 for height as default which may break your view.
  4. I will use canvasInterval variable to set and clear an interval to make <canvas> follow and unfollow the <video> element.

Logic

Here is the magical part, with the whole code.

const canvas = document.querySelector('canvas');
const video = document.querySelector('video');
const fps = 60;
const width = 1280;
const height = 720;
const canvasInterval = null;
drawImage() {
canvas.getContext('2d', { alpha: false }).drawImage(video, 0, 0, width, height);
}
canvasInterval = window.setInterval(() => {
drawImage(video);
}, 1000 / fps);
video.onpause = function() {
clearInterval(canvasInterval);
};
video.onended = function() {
clearInterval(canvasInterval);
};
video.onplay = function() {
clearInterval(canvasInterval);
canvasInterval = window.setInterval(() => {
drawImage(video);
}, 1000 / fps);
};

If you know anyone that would benefit from this guide I would love if you recommended it to them. Thank you for following this article and reading through to the end, see you on another one…

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Onur Şuyalçınkaya

Onur Şuyalçınkaya

crafting, building & shipping · swe at hey.car