A Star is Drawn

Switch To

The HTML file:

<html>
<head>
   <script src="starEngine.js" defer></script>
</head>
<body>
 <h1> A Star is Drawn</h1>
 <canvas id="drawingArea" width ="500" 
         height ="500" 
         style="border:1px solid #000000;">
 </canvas>
 <p>
 Switch To <input id="styleButton" type="button" value="Star"></input>
</body>
</html>

starEngine.js

"use strict"

const canvas = document.getElementById("drawingArea")
const CTX = canvas.getContext("2d")

const button = document.getElementById("styleButton")
button.addEventListener("click", ChangeStyle)

const SIDE_COUNT =  5
let points = []
let radius = Math.min(canvas.width/3, canvas.height/3);
let skip = 1

function ChangeStyle() {
   if (skip == 1) {
      button.value ="Pentagon"
      skip = 2
   } else {
      button.value ="Star"
      skip = 1
   }

   DrawStar()
}

class Point {
   x
   y
   constructor(xpos = 0, ypos = 0) {
      this.x = xpos
      this.y = ypos
   }

   get x() {
      return this.x
   }

   get y() {
       return this.y
   }
}

function FindSides() {
   let dAngle = 2*Math.PI/SIDE_COUNT
   let angle = 0
   for(let i =0; i < SIDE_COUNT; ++i){
      let point = new Point( Math.cos( angle) , Math.sin(angle))
      points.push(point) 
      angle += dAngle
   }
}

function DrawStar() {
    CTX.clearRect(0,0, canvas.width, canvas.height)

    let cy = canvas.height/2
    let cx = canvas.width/2

    let starPos = points.length-skip

    CTX.beginPath()
    CTX.moveTo(cx + radius * points[starPos].x, cy + radius * points[starPos].y)

    for(let i = 0; i < points.length; ++i) {
        starPos = (starPos+skip ) % points.length
        CTX.lineTo(cx + radius * points[starPos].x,
                   cy + radius * points[starPos].y)
    }
    CTX.stroke()
}


FindSides()
DrawStar()