如何用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 });```

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值