HTML and CSS Reference
In-Depth Information
Figure 4-12. Rectangles drawn on a canvas
Just like a triangle, a rectangle can also be drawn using the path-drawing techniques discussed earlier.
However, drawing a rectangle is such a commonly needed operation that there are readymade methods—
strokeRect() and fillRect() —that simplify your job. These methods accept the coordinates of the upper-
left corner of a rectangle and its width and height. The strokeRect() method draws an outline of the
rectangle, whereas fillRect() draws a filled rectangle. Listing 4-9 show how these methods are used, and
Figure 4-12 shows the resulting rectangles.
Listing 4-9. Drawing a Rectangle
var canvas = $("#MyCanvas").get(0);
var context = canvas.getContext("2d");
context.lineWidth = 5;
context.fillRect(10,10,180,50);
context.strokeRect(10,80,180,50);
n Note There is also a method— rect() —that you can use to draw rectangles. However, if you use rect() , you
also need to call stroke() or ill() to actually draw the rectangle. The strokeRect() and fillRect() methods
perform these two steps in one go.
Drawing Text
So far, you've learned to draw lines, curves, and shapes on the canvas. Often you need to incorporate text
as a part of the drawing itself, and sooner or later you'll want to draw text on the canvas. As you might
expect, the drawing context provides rich support for drawing text using the strokeText() and fillText()
methods. Additionally, you can specify the font, font size, alignment, and baseline for drawing the text.
Listing 4-10 show how to draw text with the help of these properties and methods.
 
 
Search WWH ::




Custom Search