Java Reference
In-Depth Information
context.lineWidth = 4;
The
fillRect()
method can draw a filled-in rectangle. The first two parameters are the
coordinates of the top-left corner, the third parameter is the width, and the last parameter
is the height. The following produces a filled-in blue rectangle in the top-left corner of the
canvas at coordinates (10,10) that is 100 pixels wide and 50 pixels high:
context.fillRect(10,10,100,50);
The
strokeRect()
method works in the same way, but produces a rectangle that is not
filled in. This will draw the outline of a rectangle underneath the last one:
context.strokeRect(10,100,100,50);
Straight lines can be drawn employing the
moveTo()
and
lineTo()
methods. These
methods can be used together to produce a path. Nothing will actually be drawn onto the
canvas until the
stroke()
method is called. The following example will draw a thick red
T shape onto the canvas by moving to the coordinates (150,50), then drawing a horizontal
line 30 pixels long, and finally moving to the middle of that line and drawing a vertical line
40 pixels long:
context.beginPath();
context.moveTo(130, 50);
context.lineTo(180, 50);
context.moveTo(155, 50);
context.lineTo(155, 90);
context.strokeStyle = "#c00";
context.lineWidth = 15;
context.stroke();
The
arc()
method can be used to draw an arc of a given radius from a particular point.
The first two parameters are the coordinates of the center of the arc; the next parameter is
the radius, followed by the start angle, then the finish angle (note that these are measured in
radians). The last parameter is a Boolean value that says whether the arc should be drawn
counter-clockwise. The following example will draw a yellow circle of radius 30 pixels at
center (200,200), since
Math.PI * 2
represents a full turn:
