HTML and CSS Reference
In-Depth Information
Figure 7-8. Drawing a triangle
As you can see, there are three points to the triangle: (0,0), (20,10), and (0,20). In
much the same way as you did on the square, you must calculate where the
points on the triangle should be, based on its width and height. You know that
the first point should begin at 0,0. The second point should be positioned where
x = shape width and y = shape height / 2. With this in mind, the third and final
point should be positioned where x = origin x and y = shape height. This will
create an equilateral triangle. The following code will create this:
var width = 20, height = 20, startx = 0, starty = 0;
context.beginPath();
context.fillStyle = '#A0A0A0';
context.moveTo(startx, starty);
context.lineTo((startx + width), (starty + (height / 2)));
context.lineTo(startx, (starty + height));
context.fill();
As you can see, you draw two lines to form the equilateral triangle. You do not
have to draw another line to connect the final position to the original position. By
calling context.fill() , you will automatically close the gap between the original
and final point and fill the rectangle with the context.fillStyle color. The
preceding method also takes into consideration the starting point to draw the
Search WWH ::

Custom Search