General steps for canvas polygon drawing:

  1. Find the coordinates of each point and form a path
  2. Set the state of
  3. draw

The appearance of a pentagram:

If you have a positive shape, you can use circles to calculate. Here, find the coordinates of each point with the help of two circles:

  • The Angle between the adjacent points on the outer circle of the pentacle is: 360/5 = 72
  • Similarly, the Angle between adjacent points in the inner circle of a pentagram is: 360/5 = 72
  • Thus, the Angle between the two adjacent points of the pentacle is: 72/2 = 36
  • Thus, the Angle between the rightmost point of the pentacle and the X-axis is: 90-36-36 = 18
  • So if the hypotenuse of a right triangle is R, and an Angle is 18, then the length of that Angle isR*cos(18deg)The length of the non-included side is 1R*sin(18deg)
  • So the right-hand point of the outer circle is zero(R*cos(18deg),-R*sin(18deg))The point to the left of the outer circle is theta(R*cos(18+72deg),-R*sin(18+72deg))And so on
  • So the rightmost point in the inner circle is zero(r*cos(54deg),-r*sin(54deg))The point to the left of the inner circle is theta(r*cos(54+72deg),-r*sin(54+72deg))And so on

In this way, we can write the path function of a pentagram. Note that the cosine function needs to be wrapped in a separate package to make it easier to use:

If the pentagram needs to be rotated, change it to

/ /.. Add rotate to the argument
ctx.lineTo(
  R * cos(18 + i * angle - rotate) + x,
  -R * sin(18 + i * angle - rotate) + y
);
ctx.lineTo(
  r * cos(54 + i * angle - rotate) + x,
  -r * sin(54 + i * angle - rotate) + y
);
Copy the code

Modify R and R values will have a lot of different feelings of the pentacle, the greater the gap between the two, the more sharp the pentacle, vice versa.

code

<canvas id="canvas" width="500" height="500"></canvas>
<script>
  const canvas = document.querySelector("#canvas");
  const ctx = canvas.getContext("2d");

  // Angle is converted to radians
  const getRadianFromAngle = (angle) = > (Math.PI / 180) * angle;
  // Wrap the cosine sine
  const cos = (angle) = > Math.cos(getRadianFromAngle(angle));
  const sin = (angle) = > Math.sin(getRadianFromAngle(angle));

  function getStarPath({ ctx, x, y, R, r, rotate = 0 }) {
    ctx.beginPath();
    const horn = 5;
    const angle = 360 / horn;
    for (let i = 0; i < horn; i++) {
      ctx.lineTo( R * cos(18 + i * angle - rotate) + x, -R * sin(18 + i * angle - rotate) + y );
      ctx.lineTo( r * cos(54 + i * angle - rotate) + x, -r * sin(54 + i * angle - rotate) + y );
    }
    ctx.closePath();
  }
  // 1. Set a path
  getStarPath({ ctx, x: 200.y: 200.R: 100.r: 50 });
  // 2. Set the status
  ctx.lineWidth = "3";
  ctx.strokeStyle = "#f69";
  / / 3. Draw
  ctx.stroke();
</script>
Copy the code

reference

Liuyubobobo’s Canvas drawing and animation base video liuyubobobo’s Canvas drawing detail video