How to Draw a Polygon Using the HTML5 Canvas
In this tutorial we will draw a polygon using the HTML5 canvas and a loop.
We have already seen how to draw a rectangle in this lesson and a circle in this lesson. We now take things a step further and see how we can draw a polygon by using a loop.
STEP 1
We start by creating a canvas element:
STEP 2
Next, we reference the canvas using the standard javascript getElementById function:
STEP 3
We can now create an array of point for our polygon as follows:
STEP 4
Now all we need to do is loop through the array and draw the polygon using the lineTo function as follows:
Let's break this code down a little:
Line 13: we begin the path...a standard step and hopefully straightforward
Line 14: we move the start of the polygon to the first set of co-ordinates in our array. In this case the polygon will start at point (50, 50)
Lines 15 to 17: we set up a loop to iterate through the remaining points in the array. The count starts at 2 since we have already used point 0 and point 1 for the starting co-ordinates. We increase the count by 2 each time since we will be using paired co-ordinates. In Line 16 we use the lineTo function.
So, the first time through the loop we would have:
itemctx.lineTo(polygon[item], polygon[item+1]2ctx.lineTo(100, 50)
Line 18: we close the path (which has the effect of drawing the last side of the triangle
Line 19: we stroke the path
In this example we have drawn a right-angled triangle.
STEP 5
Let's drawn another polygon, this time one with many more sides:
We end up with: