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

The 2D API

Although the canvas element is part of the HTML5 specification, the 2D API that you use to draw on it was, but is no longer, part of the specification. It was moved into its own specification at the W3C (http://dev.w3.org/html5/2dcontext).

The 2D API has a whole host of different functions and functionality, which are beyond the scope of this chapter. However, you’ll learn about and use a few of these functions in the examples throughout the chapter. You are, of course, encouraged to seek out one (or more) of the many books on the subject.

The canvas contains a drawing context, which is where the actual drawing takes place. At the moment, only a 2D context exists, but the HTML5 specification mentions that it’s likely there will be a 3D context available in the future (no date is given of course!).

To use the 2D drawing context, you need to get a handle to it. But first you need to get a handle to the canvas element, which is easily done using one of the standard JavaScript functions querySelector() or getElementById():

var canvas = document.querySelector(‘canvas’);

To get a handle on the 2D drawing context, you use the getContext() function, which accepts one argument and at the moment can only have the value 2d.

var context = canvas.getContext(‘2d’);

And there you have your context handle, which you can use to draw on the canvas. You’ll do that next using the fillRect() function.

The fillRect(x, y, w, h) function draws a simple rectangle on the canvas, and it takes four arguments: the X and Y coordinates where the rectangle is to be placed (its top-left corner), and the width and height of the rectangle.

The following code draws a black (the default colour) rectangle that is 150 × 100 pixels at the X and Y coordinates (20,20):

context.fillRect(20, 20, 150, 100);

Figure 9.1 shows the resulting rectangle.

Figure 9.1

Figure 9.1 A simple rectangle drawn on the canvas element using the fillRect() function.

The fillRect() function is one of the most basic functions of the 2D API, and you’ll use it quite often. Other functions allow you to draw lines and circles, but because you don’t need them for the main examples that follow, they aren’t discussed here.

Now that you have an understanding of the canvas element and a basic understanding of the 2D API, let’s move on to an example that allows you to take screen shots of an HTML5 video.

  • + Share This
  • 🔖 Save To Your Account