HTML5 Guidelines for Web Developers

(coco) #1
5.1 A First Example 109

Figure 5.1 Two overlapping rectangles


All figures in this chapter were created as HTML pages using Canvas and can be
found online either at the URL visible in the screen shot or via the Index page
of the companion website at http://html5.komplett.cc/code/chap_canvas/
index_en.html. Take a look at the source code!

Before we can draw on the canvas, we need to create a reference to it. The first
line in the script does exactly that. In the variable canvas and using the W3C CSS
Selectors API method document.querySelector(), it saves a reference to the first
canvas element found in the document:


var canvas = document.querySelector("canvas");


Apart from the attributes canvas.width and canvas.height, this object, also called
HTMLCanvasElement, has the method getContext(). It allows us to get to the heart
of Canvas, the CanvasRenderingContext2D, by passing 2d as context parameter:


var context = canvas.getContext('2d');


TIP
Free download pdf