Heim  >  Fragen und Antworten  >  Hauptteil

So wechseln Sie mit ClickEventListener und Vanilla JS zwischen Rot und Blau

Zuerst erstelle ich zwei Funktionen, blau und rot.

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

Hier verwende ich die Anweisung if in der For-Schleife, um einen clickEventListener zu erstellen

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. 
    }
})

Mein Fehler ist: Auch nach einem Mausklick bleibt es rot. Ich bekomme diese rote Farbe bei anderen eventListener Mausbewegungen, aber das ist nicht das Problem.

P.S.: Dies ist nicht der vollständige Code. Ich habe nur die Frage angegeben, die ich nicht lösen konnte (oben).

Ich habe den obigen Code ausprobiert, konnte aber die Farbe nicht ändern.

P粉523625080P粉523625080183 Tage vor394

Antworte allen(2)Ich werde antworten

  • 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

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

    Antwort
    0
  • StornierenAntwort