Course Links

Resources

External

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:

example example

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