Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > HTML/XHTML

  • Print
  • + Share This
This chapter is from the book

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 canvas 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 Canvas Element

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.

Table 9.1 Canvas Element Attributes




Defines the width of the canvas drawing area.


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 define 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.

  • + Share This
  • 🔖 Save To Your Account