gpt4 book ai didi

javascript - mousedown 事件仅适用于第二次点击

转载 作者:行者123 更新时间:2023-11-30 19:56:03 27 4
gpt4 key购买 nike

我有一个 mousedown 事件可以更改 Canvas 中对象的图像。但是,在第一次单击期间,除非我添加超时,否则更新功能不会更新图像。此外,我什至尝试 promise 在新图像链接之后等待,然后再调用更新函数,但我得到了相同的结果。

GameButton = new button(140, 50, 'img/GameButton.svg', 190, 460);

MyGame.canvas.addEventListener('mousedown', function(e){
if((e.clientX - GameRoom.getBoundingClientRect().left) >= GameButton.x && (e.clientX - GameRoom.getBoundingClientRect().left) <= (GameButton.x + GameButton.width) && (e.clientY - GameRoom.getBoundingClientRect().top) >= GameButton.y && (e.clientY - GameRoom.getBoundingClientRect().top) <= GameButton.y + GameButton.height){
GameButton.image.src = 'img/GameButtonDown.svg';
}
setTimeout(function(){
GameButton.update();
},3);
});


function button(width,height,img,x,y){

this.width = width;
this.height = height;
this.image = new image();
this.image.src = img;
this.x = x;
this.y = y;

this.update = function(){
ctx = MyGameRoom.ctx;
ctx.drawImage(this.image,
this.x,
this.y,
this.width, this.height);
}
}

好像update方法是在新的image.src之前触发的

最佳答案

问题是 update 只是绘制图像,但在设置 .src 后图像本身不会立即可用...您需要等待加载。一种解决方案是为自动触发更新的图像添加 load 事件处理程序。

this.image.onload = (event)=>{
this.update();
};

关于javascript - mousedown 事件仅适用于第二次点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53976191/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com