First, I create 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 use the if
statement in the For loop to create a clickEventListener
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 the mouse, it remains red. I get this red color with other eventListener
mousemove but that's not the problem.
P.S.: This is not the complete code. I've only given the one I couldn't solve (above).
I tried the above code but couldn't change the color.
The easiest option is to use a boolean variable to store your desired color and then invert it on each click:
You should maintain a reference to the next color to be drawn rather than using a loop. Additionally, if you pass the color (and context and event) as a function parameter, you can simplify the function to just one:
drawCircle
, and use that color to determine the fill color of the circle.