接下来我们需要添加一点三角函数来找到每个点的 x 和 y 位置。对于 x 位置,我们可以使用总半径乘以cos(angle),对于 y 位置半径乘以sin(angle)。 让我们把它们放在一起,添加到上面的 JavaScript 代码中:
// set the radius of the hexagon
const radius = 50;
// move the canvas to the center position
ctx.translate(cx, cy);
for (let i = 0; i < 6; i++) {
// calculate the rotation
const rotation = (Math.PI / 3) * i;
// for the first point move to
if (i === 0) {
ctx.moveTo(radius * Math.cos(rotation), radius * Math.sin(rotation));
} else {
// for the rest draw a line
ctx.lineTo(radius * Math.cos(rotation), radius * Math.sin(rotation));
}
}
// close path and stroke it
ctx.closePath();
ctx.stroke();
function drawShape(x, y, r, sides) {
// move the canvas to the center position
ctx.translate(x, y);
for (let i = 0; i < sides; i++) {
// calculate the rotation
const rotation = ((Math.PI * 2) / sides) * i;
// for the first point move to
if (i === 0) {
ctx.moveTo(r * Math.cos(rotation), r * Math.sin(rotation));
} else {
// for the rest draw a line
ctx.lineTo(r * Math.cos(rotation), r * Math.sin(rotation));
}
}
// close path and stroke it
ctx.closePath();
ctx.stroke();
// reset the translate position
ctx.resetTransform();
}