首页  >  问答  >  正文

如何使用 Vanilla JS 使用 clickEventListener 在红色和蓝色之间切换

首先,我创建两个函数蓝色和红色。

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();
}

这里我在 For 循环中使用 if 语句创建一个 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. 
    }
})

我的错误是: 即使单击鼠标后,它仍然保持红色。我通过其他 eventListener mousemove 获得了这种红色,但这不是问题。

P.S.:这不是完整的代码。我只给出了我无法解决的一个(上面)。

我尝试了上面的代码,但无法改变颜色。

P粉523625080P粉523625080183 天前390

全部回复(2)我来回复

  • P粉068486220

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

    最简单的选择就是使用一个布尔变量来存储您期望的颜色,然后在每次单击时反转它:

    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

    回复
    0
  • P粉790819727

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

    您应该维护对下一个要绘制的颜色的引用,而不是使用循环。此外,如果您将颜色(以及上下文和事件)作为函数参数传递,则可以将函数简化为一个:drawCircle,并使用该颜色来确定圆的填充颜色。

    // 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';
    });

    回复
    0
  • 取消回复