N邊形，有N個頂點、N個邊。每個邊都是由兩個頂點連線組成，因此只要找到多邊形的各頂點座標，就可以輕易地連線畫出多邊形了！而所謂的正多邊形，它的邊都是等長的，且任意相鄰兩邊之間所形成的夾角也都是相等的。

#{{{
x_i = cos(i \times {{2\pi} \over N}) \times r
}}}#

#{{{
y_i = sin(i \times {{2\pi} \over N}) \times r
}}}#

const canvas = document.getElementById("regular-polygon");

const drawPolygon = (
n = 3,
angleOffset = 0,
edge = true,
diagonal = true,
margin = 0,
) => {
if (canvas.getContext) {
const ctx = canvas.getContext("2d");

canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;

/*
// clear the canvas; it might not be necessary because the size of the canvas has been re-assigned and thus the canvas should have been cleared
ctx.clearRect(
0,
0,
canvas.width,
canvas.height,
);
*/

if (n < 3 || n > 99) {
return;
}

n = Math.floor(n); // ensure n is an integer

const centerPoint = [canvas.width / 2, canvas.height / 2];
const r = Math.min(...centerPoint) - (margin * 2);

const points = new Array(n);

const angle = 2.0 * Math.PI / n;

for (let i = 0;i < n;i++) {
const a = angleOffset + (angle * i);

const px = Math.cos(a) * r;
const py = Math.sin(a) * r;

points[i] = [px, py];
}

const drawLine = (a, b) => {
ctx.beginPath();
ctx.moveTo(centerPoint[0] + a[0], centerPoint[1] - a[1]);
ctx.lineTo(centerPoint[0] + b[0], centerPoint[1] - b[1]);
ctx.stroke();
};

if (edge) {
for (let i = n - 1;i > 0;i--) {
drawLine(points[i], points[i - 1]);
}

drawLine(points[0], points[n - 1]);
}

if (diagonal) {
const pointA = points[n - 1];

for (let j = n - 3;j > 0;j--) {
drawLine(pointA, points[j]);
}

for (let i = n - 2;i > 0;i--) {
const pointA = points[i];

for (let j = i - 2;j >= 0;j--) {
drawLine(pointA, points[j]);
}
}
}
}
};