HTML and CSS Reference
In-Depth Information
FIGURE 1-34 A rectangle drawn on the canvas using the rect method
Notice that although the parameters passed in for the top-left corner were (300,200),
which is the center of your canvas, the rectangle is off center. To center your rectangle, you
would need to do a bit of math to calculate the center based on the size of your canvas as
well as the size of your desired rectangle. The following code should center your rectangle:
ctxt.beginPath();
var x, y;
x = 150;
y = 75;
ctxt.rect(300—(x/2), 200—(y/2), x, y);
ctxt.stroke();
Now that you can draw shapes and rectangles, you can look at how you would go about
filling your shapes with colors or patterns.
Using the ill method
In this section you examine how you can fill your shapes. You have drawn various types
of shapes, but so far they have been empty. Here you'll see how to fill them with colors,
gradients, and patterns.
Filling a shape with a color is as simple as setting the illStyle property to a color and
calling the ill method. Inserting the following code before calling the stroke method fills your
shape with a blue color:
ctxt.fillStyle = "blue";
ctxt.fill();
With respect to the rect method, you get a special ill method specifically for rect called
illRect . With this method, you can create and fill your rectangle in one call:
ctxt.fillStyle = "blue";
ctxt.fillRect(300—(x / 2), 200—(y / 2), x, y);
 
Search WWH ::




Custom Search