Plotting Regular Stars

Generate Regular Stars

Once you're familiar with the simple process of generating regular polygons, it becomes easy to generate regular stars. In fact, our method is nearly identical, simply adding an internal radius requirements and one more step when generating each point.

Drawing regular stars on a Canvas

Generating stars

Our generateStar method will take size arguments, one additional added from the polygon method to account for the inner radius (the distance of the inside of each point from the centre).

The arguments are now x and y, the centre point of the star; r and r2, the outer and inner radius of the star; the number of points, and; the initial rotation of the star in radians:

function generateStar(x, y, r, r2, points, rot) {

Our star will be returned as a list of coordinates:

var coords = [];

As with the polygons, we'll calculate the angle between each point of the star. additionally, we'll calculate half of this angle, seg2, as this is the angle between an inner point and an outer point on the star:

var seg = (Math.PI * 2) / points;
var seg2 = seg / 2;

Again we'll use a loop that steps through each point on the star to add its position to our list of coords. for each step, we'll then add another point which corresponds to the next internal position of the star point:

for(var i = 0; i < points; i++) {
	coords.push([
		x + ( Math.cos( ( seg * i ) + rot ) * r ),
		y + ( Math.sin( ( seg * i ) + rot ) * r )
	]);
	coords.push([
		x + ( Math.cos( ( seg * i ) + seg2 + rot ) * r2 ),
		y + ( Math.sin( ( seg * i ) + seg2 + rot ) * r2 )
	]);
}

The second position is advanced by seg2 degrees, and is calculated at the internal radius, r2.

Our function will finish by returning this list of coords:

	return coords;
}
Page loaded in 0.007 second(s).