04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 21: Upcoming API s<br />

Figure 21-4<br />

Paths are the primary drawing mechanism for the 2D drawing context because they provide more control<br />

over what is drawn. Since paths are used so often, there is also a method called isPointInPath() , which<br />

accepts an x - coordinate and a y - coordinate as arguments. This method can be called anytime before the<br />

path is closed to determine if a point exists on the path, as shown here:<br />

if (context.isPointInPath(100, 100)){<br />

alert(“Point (100, 100) is in the path.”);<br />

}<br />

The path API for the 2D drawing context is robust enough to create very complex images using multiple<br />

fill styles, stroke styles, and more.<br />

Drawing Text<br />

Since it ’ s often necessary to mix text and graphics, the 2D drawing context provides methods to draw<br />

text. There are two methods for drawing text, fillText() and strokeText() , and each takes four<br />

arguments: the string to draw, the x - coordinate, the y - coordinate, and an optional maximum pixel width<br />

to draw. Both methods base their drawing on the following three properties:<br />

❑<br />

❑<br />

❑<br />

font — Indicates the font style, size, and family in the same manner specified in CSS, such as<br />

“ 10px Arial ” .<br />

textAlign — Indicates how the text should be aligned. Possible values are “ start ” , “ end ” ,<br />

“ left ” , “ right ” , and “ center ” .<br />

textBaseline — Indicates the baseline of the text. Possible values are “ top ” , “ hanging ” ,<br />

“ middle ” , “ alphabetic ” , “ ideographic ” , and “ bottom ” .<br />

Each of these properties has a default value, so there ’ s no need to set them each time you want to draw<br />

text. The fillText() method uses the fillStyle property to draw the text, whereas the strokeText()<br />

method uses the strokeStyle property. You will probably use fillText() most of the time, since this<br />

mimics normal text rendering on web pages. For example, the following renders a 12 at the top of the<br />

clock created in the last section:<br />

context.font = “bold 10px Arial”;<br />

context.textAlign = “center”;<br />

context.textBaseline = “middle”;<br />

context.fillText(“12”, 100, 80);<br />

687

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!