Falcon80 Logo
Drawing closed shapes on canvas

Drawing polygons and other closed shapes
 
We already learnt the concept of paths and straight lines on canvas. You can draw any shape involving straight lines using these two concepts. As an example, we will see how how to draw a triangle. A triangle is defined by three points (x1,y1), (x2,y2), (x3,y3).
Triangle on a canvas
To draw a triangle on canvas,

1. Move to point (x1,y1)
2. From (x1,y1), draw a line to (x2,y2)
3. From (x2,y2), draw a line to (x3,y3)
4. Close the triangle by drawing a line from (x3,y3) back to (x1,y1)
 
Required Methods

You will need the following methods to draw a triangle.
  • strokeStyle:
This method can be used to define the colour of any figure on the canvas. Here, we will use it to define the colour of the triangle we are about to draw. If you don't mention the strokeStyle, the default colour is black.
  • moveTo(x1,y1):
The moveTo() method positions the pen on canvas at any desired pixel location. Here, we will use it to define a starting point (x1,y1) for our triangle.
  • lineTo(x2,y2):
The lineTo() method will draw a line from the last point in the path to the point specified in the method. We will use this method to draw the lines from (x1,y1) to (x2,y1), (x2,y2) to (x3,y3), and from (x3,y3) back to (x1,y1).
  • stroke():
The moveTo() and lineTo() methods will only define the shape of the figure we are about to draw. The stroke() method does the actual drawing 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 line
ctx.strokeStyle = "red";

//define the starting point of line1 (x1,y1)
ctx.moveTo(100,100);

//define the end point of line1 (x2,y2)
ctx.lineTo(300,100);

//define the end point of line2 (x3,y3)
ctx.lineTo(200,200);

//define the end point of line3 (x1,y1). We are back to where we started
ctx.lineTo(100,100);

//draw the points that makeup the triangle - (x1,y1) to (x2,y2), (x2,y2) to (x3,y3),  and (x3,y3) to (x1,y1)
ctx.stroke();
}
}
  </script>
  </head>
<body onload="init();">
<canvas id="canvas" width="900" height="500"></canvas><br>
</body>
</html>

Try Code