Plotting Regular Polygons

Regular Polygons source code

<!DOCTYPE html>
<html>
<head>

<script type="text/javascript">

function generatePolygon(x, y, r, points, rot) {
	var coords = [];
	var seg = (Math.PI * 2) / points;

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

	return coords;
}

function drawPolygon(x, y, r, points, rot) {
	var ctx = document.getElementById("viewshapes").getContext('2d');

	var poly = generatePolygon(x, y, r, points, rot);

	ctx.beginPath();
	ctx.moveTo(poly[0][0], poly[0][1]);

	for(var i = 1; i < poly.length; i++) {
		ctx.lineTo(poly[i][0], poly[i][1]);
	}

	ctx.closePath();
	ctx.stroke();
}

window.addEventListener("load", function () {
	drawPolygon(100, 100, 80, 5, 0);			// Pentagon
	drawPolygon(180, 150, 80, 4, Math.PI/4);	// Square
	drawPolygon(260, 120, 80, 8, Math.PI);		// Octagon
	drawPolygon(360, 150, 80, 3, Math.PI/2);	// Triangle
});

</script>
</head>
<body>

<canvas id="viewshapes" width="600" height="300">
If you see this text, please switch to a browser that supports canvas
elements.</canvas>

</body>
</html>
Page loaded in 0.007 second(s).