How to switch between red and blue using clickEventListener using Vanilla JS
P粉523625080
P粉523625080 2024-04-03 20:19:03
0
2
462

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粉523625080
P粉523625080

reply all(2)
P粉068486220

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
P粉790819727

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';
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!