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.

Drawing Rectangles<br />

Chapter 21: Upcoming API s<br />

The only shape that can be drawn directly on the 2D drawing context is the rectangle. There are<br />

three methods for working with rectangles: fillRect() , strokeRect() , and clearRect() . Each<br />

of these methods accepts four arguments: the x - coordinate of the rectangle, the y - coordinate of the<br />

rectangle, the width of the rectangle, and the height of the rectangle. Each of these arguments is<br />

considered to be in pixels.<br />

The fillRect() method is used to draw a rectangle that is filled with a specific color onto the<br />

canvas. The fill color is specified using the fillStyle property, which starts out equal to black<br />

( “ #000000 ” ). You can set this property to any color specified in six hex digits or by using the CSS rgb()<br />

and rgba() formats. Here is an example:<br />

var drawing = document.getElementById(“drawing”);<br />

//make sure < canvas > is completely supported<br />

if (drawing.getContext){<br />

var context = drawing.getContext(“2d”);<br />

/*<br />

* Based on Mozilla’s documentation:<br />

* http://developer.mozilla.org/en/docs/Canvas_tutorial:Basic_usage<br />

*/<br />

//draw a red rectangle<br />

context.fillStyle = “#ff0000”;<br />

context.fillRect(10, 10, 50, 50);<br />

}<br />

//draw a blue rectangle that’s semi-transparent<br />

context.fillStyle = “rgba(0,0,255,0.5)”;<br />

context.fillRect(30, 30, 50, 50);<br />

This code first sets the fillStyle to red and draws a rectangle located at (10,10) that ’ s 50 pixels tall and<br />

wide. Next, it sets the fillStyle to a semi - transparent blue color using rgba() format and draws<br />

another rectangle that overlaps the first. The result is that you can see the red rectangle through the blue<br />

rectangle (see Figure 21 - 1 ).<br />

Figure 21-1<br />

683

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

Saved successfully!

Ooh no, something went wrong!