【实例】规则多变形的绘制

358 阅读1分钟

绘制原理 1627701499(1).png 实现样例

1627702828(1).png

具体代码

  • 实现的主要方式是根据弧度来获取到点的位置,然后进行描边,不过这里所说的多变形都是正多边型
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>多边型</title>
  <style>
    canvas{
      border: 1px solid #eee;
    }
  </style>
</head>
<body>
  <canvas id="myCanvas" width="600" height="600"></canvas>
  <script>
    let canvas = document.getElementById('myCanvas')
    let ctx = canvas.getContext('2d')

    let w = canvas.width ,
        h = canvas.height

    function drawPolygon(ctx,polygon = 4,strokeStyle,fillStyle,x,y,r){
      ctx.save()
      ctx.fillStyle = fillStyle
      ctx.strokeStyle = strokeStyle
      ctx.beginPath()
      let angle = 0
      let stepAngle = 360 / polygon * Math.PI / 180  // -- 每一步增加的弧度
      ctx.moveTo(x + r , y)
      for(let i = 1 ;i <= polygon ;i++){
        angle += stepAngle 
        let dx = x + Math.cos(angle) * r , dy = y + Math.sin(angle) * r
        ctx.lineTo(dx,dy)
      }
      ctx.stroke()
      ctx.closePath()
      ctx.restore()
    }
    drawPolygon(ctx,6,'green','white',w/2 ,h/2 , 100)
  </script>
</body>
</html>