search

Home  >  Q&A  >  body text

How to switch between red and blue using clickEventListener using Vanilla JS

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.

P粉523625080P粉523625080261 days ago517

reply all(2)I'll reply

  • P粉068486220

    P粉0684862202024-04-04 09:48:41

    The easiest option is to use a boolean variable to store your desired color and then invert it on each click:

    function drawBlueCircle() {
      console.log('drawBlueCircle called')
    }
    
    function drawRedCircle() {
      console.log('drawRedCircle called')
    }
    
    // This variable tracks which color we are up to
    let isBlue = true
    
    // Added the listener to 'window' for the sake of the example
    window.addEventListener('click', function(event) {
      // Run the expected function
      if (isBlue) {
        drawBlueCircle()
      } else {
        drawRedCircle()
      }
      
      // Invert the next color
      isBlue = !isBlue
    })
    Click anywhere

    reply
    0
  • P粉790819727

    P粉7908197272024-04-04 00:09:03

    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.

    // Pass in the context, event, and colour to the
    // function so you can use them
    function drawCircle(ctx, event, color) {
      ctx.fillStyle = color;
      ctx.beginPath();
      ctx.arc(event.x, event.y, 50, 0, Math.PI *2);
      ctx.fill();
    }
    
    const canvas = document.querySelector('canvas');
    const ctx = canvas.getContext('2d');
    
    // Initialise the color
    let color = 'red';
    
    canvas.addEventListener('click', event => {
      
      // Draw a circle with the current colour
      drawCircle(ctx, event, color);
    
      // Switch the color
      color = color === 'red' ? 'blue' : 'red';
    });

    reply
    0
  • Cancelreply