HTML5 Multimedia: Using Video with Canvas
In addition to native multimedia, one of the most talked about capabilities that HTML5 brings to the web table is the ability to draw and manipulate graphics using JavaScript via the new canvas element. The element defines an area on a web page that you can draw on using a JavaScript API.
Canvas and its corresponding API have many uses, from copying media and drawing simple graphs to filling colours, directly manipulating pixels, and creating complex games that are played inside the browser without needing a third-party plugin.
You can also use multimedia elements in interactions with canvas and the API. This chapter briefly explores some of these simple interactions, with, as always, fully explained examples.
The brief chapter introduction told you what you can use the canvas element for and that it’s actually quite useless on its own. However, it is very easy to use and only has two possible attributes, which are listed in Table 9.1.
The Canvas Element
Table 9.1 Canvas Element Attributes
attribute |
Description |
width |
Defines the width of the canvas drawing area |
height |
Defines the height of the canvas drawing area |
That’s it, really! You can, of course, also define the canvas’s dimensions using CSS or JavaScript. And just like every other HTML element, the position, borders, and so on of the canvas element can be defined via CSS.
Defining a canvas element on your web document is as simple as this:
<canvas width=”500” height=”500”></canvas>
Of course, leaving it at that renders absolutely nothing of interest on the web page, so you probably wouldn’t see a thing because it would render as a blank space. You could add a border to it via CSS so you could actually view it when you are experimenting.
The canvas is a two-dimensional grid, and as such has two axes, X and Y. To defne a position within the canvas, you specify two coordinates on this grid (X,Y). The top-left corner position of the grid is considered “home” and has the coordinates (0,0).
But to actually do anything useful with the canvas element, you need to invoke the 2D JavaScript API, which is what you’ll do next.