[Solved] How can I create five pointed stars in canvas using function? [closed]


Make a loop of the number of points in the shape. In the case of a 5 pointed star that is 10 points because you have the outer points to make the spikes and the inner points which come back into the shape.

Inside the loop you find each consecutive point (x, y coordinate) to draw a line to e.g. using ctx.lineTo(x, y);.

To do this I would use sine and cosine which looks like this:

  const x = xOffset+Math.sin(angle)*radius;
  const y = yOffset+Math.cos(angle)*radius;

You just need to provide the offsets, the angle, and the radius, and it will give you the x, y coordinates.

Start with a loop for each point in the star:

for(let i = 0; i < 10; i ++){ ... }

And use the sine/cosine code to get the point’s x,y coordinate, so you can draw a line to it with ctx.lineTo(x,y).

Sine and cosine are functions that take an angle in radians. That is an angle between 0 and 2pi or -pi/2 to +pi/2.

To get the angle around the center of our star which these functions will understand, you need to normalize i to between 0 and 1 instead of 0 and 10, so you divide it by 10. Then you multiply this by 2pi to get a value between 0 and 2pi. This now gives you an angle for each iteration of the loop which makes a full circle.

Next you want to get the radius, which is simply a pixel distance value you provide to give the star size. However, the inner points will need to be less than the max radius so that it actually makes spikes. To do this you can use the modulo operator to determine if you are in an odd or even iteration in the loop. E.g. i%2. Use this value to change the radius at which the point will be made.

const canv = document.getElementById('c');
const ctx = canv.getContext('2d');
const w = window.innerWidth;
const h = window.innerHeight
canv.width = w;
canv.height = h;
ctx.clearRect(0,0,w,h);
//offset x,y, size, spokes, rotation 0 to 1.
function star(ox, oy, s = 10, n = 5, r = 0.25){
  ctx.beginPath();
  
  for(let i=0;i<n*2;i++){
    let rotation = Math.PI*2*r;
    let angle = (i/(n*2))*Math.PI*2+rotation;
    let dist = s*(i%2)+s;
    let x = ox+Math.cos(angle)*dist;
    let y = oy+Math.sin(angle)*dist;
    if(i === 0) {
      ctx.moveTo(x, y);
      continue; //skip
    }
    ctx.lineTo(x, y);
  }
  ctx.closePath();
}

ctx.fillStyle="magenta";
star(w/2, h/2, 10, 4, 0.125);
ctx.fill();

ctx.fillStyle="red";
star(w*0.2, h*0.2, 5, 5);
ctx.fill();

ctx.fillStyle="orange";
star(w*0.33, h*0.33, 20, 5);
ctx.fill();

ctx.fillStyle="yellow";
star(w*0.66, h*0.25, 30, 6);
ctx.fill();

ctx.fillStyle="green";
star(w*0.2, h*0.75, 40, 7);
ctx.fill();

ctx.fillStyle="cyan";
star(w*0.82, h*0.8, 50, 8, 1/16);
ctx.fill();
canvas {
 position: absolute;
 left: 0;
 top: 0;
 width: 100%;
 height: 100%;
 overflow: hidden;
 background-color: black;
}
<canvas id="c"></canvas>

1

solved How can I create five pointed stars in canvas using function? [closed]