This lab introduces regular polygons in a way that prepares you for transformations later on. It will also give you some experience with JavaScript "Math" functions and built-in line drawing. For this lab, use pair programming with your random partner (i.e. use one person's computer, then email the code to the other person afterward).
Study the code
Fork the starter code at lab2.html and look at the Javascript. Study the arguments to regularPolygon and make sure each of them makes sense. The first step is to set graphics.strokeStyle to the chosen line color.
Compute θ
As discussed in class, we want to find θ such that θ*n = 360 degrees, where n is the number of sides of the polygon. We'll need to use radians in JavaScript, so you can use:
2*Math.PI // 360 degrees
Compute the start point
When using lines to create a polygon in JavaScript, we need to specify the start point using graphics.moveTo(startX,startY). Uncomment this line and fill in the correct x and y values for the start point.
For loop over the sides
Finally, create a for loop that goes over all n sides. Inside the for loop, first compute the angle based on θ*i. Then compute the x and y coordinates of the new point. Then use graphics.lineTo(x,y) to add this point to the path.
Call your regular polygon function from within draw(). Experiment with a variety of number of sides, sizes, and colors. Here are some examples with n=5 and n=10:
How many sides does a polygon need to have before it is indistinguishable from a circle?
Try adding a parameter α to all the vertex angles, to get a rotated polygon.
You do not have to turn this lab in, but make sure that everyone in your group has a working copy by the end of the lab. We will build on this work for Homework 2 (filling the polygons!)
Extensions
- If you have time, and you have finished your line-drawing function from the first homework assignment, put it to use. Make a second polygon-drawing function that calls your drawLine function instead of using the built-in ones. Do the results differ in any way between the two? Why?
- Experiment with other shapes besides regular polygons. Can you come up with functions that can quickly generate a wide variety of shapes from a small number of parameters?
- Experiment with filled polygons. particularly concave and complex ones. Can you make star shapes? (Hint: use polygon vertices, but connect them in a skipping pattern, e.g. 2,4,1,3,5.)
- Use your polygons to draw an interesting scene or picture.