Required Methods
You will need the following methods to draw a rectangle.
This attribute is used to define the colour of any figure that is drawn on the canvas. Here, we will use it to define the colour of the rectangle we are about to draw.
The strokeStyle() attribute should be paired with either the stroke() method or
the strokeRect() method. If you do not specify the strokeStyle, the default colour
will be black.
This attribute defines the fill-colour of any closed shape drawn on the canvas. It is always paired with the fill() method or fillRect() method. If you do not specify
the fillStyle, the default colour will be black.
- strokeRect(x,y, length, breath):
This method draws the outline of the rectangle in the colour specified by the strokeStyle
attribute. It takes as parameters, the point where the rectangle starts (x,y), the length of the rectangle and the breath of the rectangle.
- fillRect(x,y, length, breath):
This method draws a rectangle that is filled by the colour specified in fillStyle attribute. It takes as parameters, the point where the rectangle starts (x,y), the
length of the rectangle and the breath of the rectangle.
- rect(x,y, length, breath):
This method defines the outline of the rectangle in the colour specified by the
strokeStyle attribute. It takes as parameters, the point where the rectangle starts
(x,y), the length of the rectangle and the breath of the rectangle. Note that this
method() by itelf will not draw on the canvas. You will have to use the stroke()
method to draw the actual rectangle on the canvas.
- clearRect(x,y, length, breath):
This method clears a rectanglular area of any size on the canvas. It takes as parameters,
the point where the rectangular clearing area starts (x,y), the length of the rectangular
area and the breath of the rectangular area.
|
|
<html>
<head>
<script type="application/javascript">
function init() {
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
//define the colour of the rectangle outline
ctx.strokeStyle = "green";
//define the fill colour of the rectangle
ctx.fillStyle = "green";
//draw the outline of a rectangle using the strokeRect() method
ctx.strokeRect(50,50,100,50);
// draw a colour-filled rectangle using the fillRect() method
ctx.fillRect(200,50,100,50);
// Draw a rectangle using the rect() method
ctx.rect(350,50,100,50);
ctx.stroke();
// Draw a rectangle using the fillRect() method
ctx.fillRect(500,50,100,50);
// Clear a rectangular space within the previously drawn rectangle
ctx.clearRect(540,60,20,20);
}
}
}
</script>
</head>
<body onload="init();">
<canvas id="canvas" width="900"
height="500"></canvas><br>
</body>
</html>
|
Try Code
|
|