HTML5 Video and Canvas – a little game



Works in Safari, Chrome and Firefox

How does it work?

Mostly witchcraft but also Javascript and some of the new APIs offered to us by HTML5.

We start by embedding a video using the wonderful <video> tag. Then we hide the video. Madness. After that we create twelve new friends using the fabulous <canvas> tag. These twelve canvasses each contain a portion of the video and act as the tiles for our game.

The code below show how you would take a 100×100 chunk of the video starting at the top left and paint it onto a canvas.

var tile = document.getElementById('tile');
var ctx = tile.getContext('2d');
var video document.getElementById('video');
ctx.drawImage(video, 0, 0, 100, 100);

The getContext method of our canvas gives us access to its rendering functions. These functions allow us to draw shapes and lines and colour them in (amongst other things) – in this example we are using drawImage. drawImage takes a source as its first argument (our video) and then a lot of anonymous looking numbers. These numbers are explained very well by the snappily named Web Hypertext Application Technology Working Group.

Our little game isn’t that dissimilar to the example code above. The main difference being that we employ some Mad Loop Action. Thirty times a second (one iteration for each frame of the video) we render our twelve tiles. That means we are calling drawImage 360 times a second – this is why your CPU usage has shot up if you’re using Firefox.

Topics: Development Tags: , , , ,
Comments: none so far

Post a Comment

Your email is never shared. Required fields are marked *

*
*