Exercise 1.2

We want to draw an equilateral triangle near the center of the page. First, we will only draw the outline. Since the letter size is 8.5 inches by 11 inches, we will say that the center point of the page is (4.25 inches, 5.5 inches). In points, the center is approximately (298 points, 385 points).

It seems to me that the easiest way of tracing a path around the equilateral triangle is to move to the corner that is axis-aligned first (the top corner), and then move to the left and right corners. Using the law of sines, the knowledge that lines that intersect the center bisect the corner angles, and that the corner angles are each 60 degrees, we can find the dy that we need to travel if we start in the center to get to the top corner.

sin(30 degrees) / dy = sin(120 degrees) / 100 points dy is approximately equal to 58 points.

We already know that the dx to travel to the left and right corner had the magnitude of half of the side length.

|dx| = 50 points.

Finally, we need to know the height of the triangle, which is the distance the path has to travel in the y direction to go from the top corner to either the left or right corners of the triangle. We can do this by spliting the equilateral triangle in half to get a 30-60-90 triangle.

h = 50 points * sqrt(3) h is approximately equal to 87 points.

Now we have enough information to draw the outline of the triangle.

write "example_1.ps"
0 setgray newpath 298 443 moveto % center plus dy to get top corner -50 -87 rlineto % left corner 100 0 rlineto % right corner -50 87 rlineto % top corner closepath stroke showpage

We can build and display the result below:

build example_1.png example_1.ps
gs -o example_1.png -sDEVICE=pngalpha example_1.ps
picture example_1.png

To fill the equilateral triangle with a color, we will use setrgbcolor to fill the triangle red. We will need to draw the outline and fill the triangle separately.

write "example_2.ps"
0 setgray newpath 298 443 moveto % center plus dy to get top corner -50 -87 rlineto % left corner 100 0 rlineto % right corner -50 87 rlineto % top corner closepath stroke % black outline 1 0 0 setrgbcolor newpath 298 443 moveto % center plus dy to get top corner -50 -87 rlineto % left corner 100 0 rlineto % right corner -50 87 rlineto % top corner closepath fill % red fill showpage

We can build and display the result below:

build example_2.png example_2.ps
gs -o example_2.png -sDEVICE=pngalpha example_2.ps
picture example_2.png