如何使用 Vanilla JS 使用 clickEventListener 在红色和蓝色之间切换
P粉523625080
P粉523625080 2024-04-03 20:19:03
0
2
362

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

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

全部回复(2)
P粉068486220

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

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

您应该维护对下一个要绘制的颜色的引用,而不是使用循环。此外,如果您将颜色(以及上下文和事件)作为函数参数传递,则可以将函数简化为一个: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';
});
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!