如何用canvas绘制五角星
如何用canvas绘制五角星
/** 以(x, y)为圆心,起始角度为startAngle,绘制一个半径为radius,圆心角为pointAngle的扇形 **/
function drawStarPoint({ x, y, radius, startAngle, pointAngle }) {
ctx.beginPath();
ctx.arc(x, y, radius, startAngle, startAngle + pointAngle);
ctx.lineTo(x, y);
ctx.closePath();
ctx.fill();
}
/** 绘制多角星 **/
function drawPointStar({
radius,
x,
y,
startAngle = 0,
points = 5,
pointAngle = Math.PI / 6,
}) {
// 默认以90度作为第一个角起始位置
const baseStartAngle = Math.PI / 2;
for (let i = 0; i < points; i++) {
const currentBaseAngle =
baseStartAngle + startAngle + (2 * i * Math.PI) / points;
const pointAngleStart = currentBaseAngle - pointAngle / 2;
// 底层使用扇形绘制实现,因此需要使用三角函数进行坐标补正,将扇形对圆心做中心对称变换
drawStarPoint({
x: x - Math.cos(-currentBaseAngle) * radius,
y: y + Math.sin(-currentBaseAngle) * radius,
radius,
startAngle: pointAngleStart,
pointAngle,
});
}
}
const canvas = document.getElementById('flag');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'yellow';
const x = canvas.width / 2;
const y = canvas.height / 2;
const radius = canvas.width / 8;
const angle = 0;
drawPointStar({ radius, x, y, points: 5 });```