I am working on an assignment where I have to draw a four point star and create a for
loop to generate between 1 and 100 stars depending on the user input. Here are the instructions:
The requirements of painting stars are as follows:
- a. for loop should be used in this function.
- b. The number of stars should match the user’s input. If the user’s input is not a number or not from 1 to 100, show an alert message to ask the user to input a valid number.
- c. The center of each star is randomly located on the canvas.
- d. The color of each dot is randomly generated.
- e. The distance between the far point and the center is randomly generated between 5 and 50. The distance between the near point and the center is ΒΌ of the distance between far point and the center.
But mine is not working. I am not sure where the values of part d and e should be entered. I not sure if the way I created it is right. Could someone please help me here?
const ctx = document.querySelector("canvas").getContext("2d"),
b1 = document.getElementById("b1");
b1.addEventListener("input", paintStar);
function paintStar() {
ctx.clearRect(
0,
0,
800,
400
);
for (let i = 1; i <= b1.value; i++) { /*this loop is not working correctly, not multiplying according to my b1.value*/
x = Math.floor(Math.random() * 800) + 1;
y = Math.floor(Math.random() * 400) + 1;
d = Math.random() * 45 + 5; /*number between 5 and 50*/
e = d / 4; /*1/4 of size*/
/*I created my start using rotation and one more FOR loop*/
ctx.beginPath();
ctx.translate(x, y); /* Here I put my X and Y to change the positions of the starts on my canvas*/
ctx.beginPath();
ctx.rotate((-90 * Math.PI) / 180);
ctx.moveTo(50, 0);
for (let j = 1; j <= 4; j++) {
ctx.rotate((45 * Math.PI) / 180);
ctx.lineTo(20, 0); /*I tried to put D and E here in Lineto, but did not work out*/
ctx.rotate((45 * Math.PI) / 180);
ctx.lineTo(50, 0);
}
ctx.fillStyle =
"rgb(" +
Math.floor(Math.random() * 256) +
"," +
Math.floor(Math.random() * 256) +
"," +
Math.floor(Math.random() * 256) +
")";
ctx.fill();
}
}
<input id="b1" type="number" placeholder="b1"/>
<canvas width="800" height="400"></canvas>