HTML and CSS Reference
In-Depth Information
The Basic Rectangle Shape
Let's get our feet wet by looking at the single primitive, built-in geometric shape on Can-
vas—the rectangle. On Canvas, basic rectangle shapes can be drawn in three different ways:
filling, stroking, or clearing. We can also build rectangles (or any other shape) by using paths,
which we will cover in the next section.
First, let's look at the API functions used for these three operations:
fillRect(x,y,width,height)
Draws a filled rectangle at position x , y for width and height.
strokeRect(x,y,width,height)
Draws a rectangular outline at position x , y for width and height. This makes use of the
current strokeStyle , lineWidth , lineJoin , and miterLimit settings.
clearRect(x,y,width,height)
clearRect(x,y,width,height)
Clearsthespecifiedareaandmakesitfullytransparent(usingtransparentblackasthecol-
or) starting at position x , y for width and height.
Before we can use any of these functions, we will need to set up the fill or stroke style that
will be used when drawing to the canvas.
Themostbasicwaytosetthesestylesistouseacolorvaluerepresentedbya24-bithexstring.
Here is an example from our first demonstration:
context . fillStyle = '#000000' ;
context . strokeStyle = '#ff00ff' ;
In Example 2-1 , the fill style is simply set to be the RGB color black, while the stroke style is
a classic purple color. The results are shown in Figure 2-1 .
Example 2-1. Basic rectangles
function
function drawScreen () {
context . fillStyle = '#000000' ;
context . strokeStyle = '#ff00ff' ;
context . lineWidth = 2 ;
context . fillRect ( 10 , 10 , 40 , 40 );
context . strokeRect ( 0 , 0 , 60 , 60 );
context . clearRect ( 20 , 20 , 20 , 20 );
}
Search WWH ::




Custom Search