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

huangapple go评论60阅读模式
英文:

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

问题

以下是代码部分的翻译:

首先,我创建了两个函数 Blue 和 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();
}

在这里,我创建了一个带有 if 语句的 clickEventListener,并在 For 循环中使用它:

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() // 这里我尝试使用 for 循环改变我的点击行为。
    }
})

我的错误是:
即使点击了鼠标,它仍然是红色的。这个红色是我通过其他的 mousemove 事件监听器得到的,但这不是问题的原因。

P.S.:这不是整个代码。我只提供了我无法解决的部分(上面的部分)。

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

英文:

First, I am creating two functions Blue and red.

function drawBlueCircle(){
    ctx.fillStyle = &#39;blue&#39;;
    ctx.beginPath();
    ctx.arc(mouse.x,mouse.y,50,0,Math.PI *2)
    ctx.fill();
}

function drawRedCircle(){
    ctx.fillStyle = &#39;red&#39;
    ctx.beginPath();
    ctx.arc(mouse.x,mouse.y,50,0,Math.PI * 2);
    ctx.fill();
}

Here I am creating a clickEventListener with if statements in For loops


canvas.addEventListener(&#39;click&#39;,function(event){
    mouse.x = event.x,
    mouse.y = event.y
    
    for(let i=0;i&lt;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 my mouse, it stays red.This red I have through other eventListener mousemove but that's not the problem .

P.S.: this is not the Entire code. I have given only the one I couldn't solve(above).

I tried above code and I couldn't change color.

答案1

得分: 2

以下是您要翻译的内容:

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

function drawBlueCircle() {
  console.log('drawBlueCircle called')
}

function drawRedCircle() {
  console.log('drawRedCircle called')
}

// 这个变量跟踪我们目前使用的颜色
let isBlue = true

// 为了示例的完整性,将监听器添加到 'window' 上
window.addEventListener('click', function(event) {
  // 运行期望的函数
  if (isBlue) {
    drawBlueCircle()
  } else {
    drawRedCircle()
  }
  
  // 反转下一个颜色
  isBlue = !isBlue
})
点击任何地方
英文:

The easiest option is just to have a boolean variable storing your expected colour, and then invert it each time you click:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

function drawBlueCircle() {
  console.log(&#39;drawBlueCircle called&#39;)
}

function drawRedCircle() {
  console.log(&#39;drawRedCircle called&#39;)
}

// This variable tracks which color we are up to
let isBlue = true

// Added the listener to &#39;window&#39; for the sake of the example
window.addEventListener(&#39;click&#39;, function(event) {
  // Run the expected function
  if (isBlue) {
    drawBlueCircle()
  } else {
    drawRedCircle()
  }
  
  // Invert the next color
  isBlue = !isBlue
})

<!-- language: lang-html -->

Click anywhere

<!-- end snippet -->

答案2

得分: 0

你现在尝试做的事情,从我理解的情况来看,是在每次点击时在“drawRed”和“drawBlue”之间切换。

我认为你的代码不起作用的原因是因为每次点击时基本上都会运行for循环。在循环运行之后,要么选择了“drawBlue”,要么选择了“drawRed”,这意味着只有其中一个会运行。而且它每次都会产生相同的结果(因为出于某种原因,你在事件对象上运行了一个循环)。

你可以尝试的做法是在addEventListener外部设置一个布尔标志。然后,在回调函数中,根据这个布尔标志触发drawBlueCircledrawRedCircle。之后,你可以切换它的值。

类似这样的代码:

let isRed = false;

canvas.addEventListener('click', function(event){
    mouse.x = event.x;
    mouse.y = event.y;

    if (isRed) {
        drawRedCircle();
    } else {
        drawBlueCircle();
    }

    isRed = !isRed;
})
英文:

What you're trying to do, from what I understand , is toggle between drawRed and drawBlue with each click.

The reason, I think, your code isn't working is because essentially every time you click, that for loop is run. After the loop is run, either drawBlue or drawRed is 'selected', meaning, only one of them is run. And it will give the same result every time (because, for whatever reason, you're running a loop through the event object).

What you can try to do is have a boolean flag set outside the addEventListener. Then, in the callback function, you can fire either drawBlueCircle or drawRedCircle based on this boolean flag. After that you can toggle its value.

Something like this :

let isRed = false;

  canvas.addEventListener(&#39;click&#39;,function(event){
      mouse.x = event.x;
      mouse.y = event.y;

    if(isRed){
      drawRedCircle()
    }
    else {
    drawBlueCircle()
    }

    isRed = !isRed;
})

答案3

得分: 0

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

// 将上下文、事件和颜色传递给函数,以便您可以使用它们
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');

// 初始化颜色
let color = 'red';

canvas.addEventListener('click', event => {
  
  // 使用当前颜色绘制一个圆
  drawCircle(ctx, event, color);

  // 切换颜色
  color = color === 'red' ? 'blue' : 'red';
});
<canvas width="400" height="400"></canvas>
英文:

Rather than using a loop you should maintain a reference to the next colour to be drawn. In addition if you pass in the colour (along with the context, and the event) as a function argument you can reduce your functions to one: drawCircle, and use that colour to determine the circle's fill colour.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

// 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(&#39;canvas&#39;);
const ctx = canvas.getContext(&#39;2d&#39;);

// Initialise the color
let color = &#39;red&#39;;

canvas.addEventListener(&#39;click&#39;, event =&gt; {
  
  // Draw a circle with the current colour
  drawCircle(ctx, event, color);

  // Switch the color
  color = color === &#39;red&#39; ? &#39;blue&#39; : &#39;red&#39;;
});

<!-- language: lang-html -->

&lt;canvas width=&quot;400&quot; height=&quot;400&quot;&gt;&lt;/canvas&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月15日 17:09:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76480909.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定