First, I am creating two functions Blue and red.
function drawBlueCircle(){
ctx.fillStyle = 'blue';
ctx.beginPath();
ctx.arc(mouse.x,mouse.y,50,0,Math.PI *2)
ctx.fill();
}
function drawRedCircle(){
ctx.fillStyle = 'red'
ctx.beginPath();
ctx.arc(mouse.x,mouse.y,50,0,Math.PI * 2);
ctx.fill();
}
Here I am creating a clickEventListener with if
statements in For loops
canvas.addEventListener('click',function(event){
mouse.x = event.x,
mouse.y = event.y
for(let i=0;i<event.length;i++){
(i%2==0)? drawBlueCircle():drawRedCircle() // here i am trying to alter my clicks using for loops.
}
})
My error is :
even after clicking my mouse, it stays red.This red I have through other eventListener
mousemove but that’s not the problem .
P.S.: this is not the Entire code. I have given only the one I couldn’t solve(above).
I tried above code and I couldn’t change color.
3
Answers
The easiest option is just to have a boolean variable storing your expected colour, and then invert it each time you click:
What you’re trying to do, from what I understand , is toggle between
drawRed
anddrawBlue
with each click.The reason, I think, your code isn’t working is because essentially every time you click, that for loop is run. After the loop is run, either
drawBlue
ordrawRed
is ‘selected’, meaning, only one of them is run. And it will give the same result every time (because, for whatever reason, you’re running a loop through the event object).What you can try to do is have a boolean flag set outside the
addEventListener
. Then, in the callback function, you can fire eitherdrawBlueCircle
ordrawRedCircle
based on this boolean flag. After that you can toggle its value.Something like this :
Rather than using a loop you should maintain a reference to the next colour to be drawn. In addition if you pass in the colour (along with the context, and the event) as a function argument you can reduce your functions to one:
drawCircle
, and use that colour to determine the circle’s fill colour.