Falcon80 Logo
Drawing squares on a canvas

Defining a Square
You can use the same methods that you used to draw a rectangle to draw a square viz., strokeRect(), fillRect() and rect().

Similar to a rectangle, a square is defined by its starting point (x,y), length and breath.
Arc on a canvas
Note that for a square, length = breath
 
Required Methods

You will need the following methods to draw a square.
  • strokeStyle:
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 square 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.
  • fillStyle:
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(pt1, length, breath):
This method draws the outline of the rectangle, and takes as parameters, the point where the rectangle starts, the length of the rectangle and the breath of the rectangle. Since we are drawing a square here, the length and breath should be the same.
  • fillRect(pt1, 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, the length of the rectangle and the breath of the rectangle. Since we are drawing a square here, the length and breath should be the same.
  • rect(pt1, 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. To draw a square, make length = breath. Note that this method() by itelf will not draw on the canvas. You will have to use the stroke() method to draw the actual square on the canvas.
<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 square
ctx.strokeStyle = "green";
ctx.fillStyle = "green";

// Draw the outline of a square
ctx.strokeRect(50,50,100,100);

// Draw a square using the fillRect() method and fill it with the colour specified by the fillStyle attribute
ctx.fillRect(200,50,100,100);

// Draw a square using the rect() method
ctx.rect(350,50,100,100);
ctx.stroke();

}
}
  </script>
</head>
<body onload="init();">
<canvas id="canvas" width="900" height="500"></canvas><br>
</body>
</html>

Try Code