简体   繁体   中英

mousedown event only works on second click

I have a mousedown event that change the image of an object in a canvas. However, during the first click the update function doesn't update the image unless I add a Timeout. Futhermore, I even tried with a promise to wait after the new image link before to call the update function, but I get the same result.

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

It seems like the update method is triggered before the new image.src

The problem is that update just draws the image but the image itself is not immediately available after setting .src ... you need to wait for the loading. A solution could be adding an event handler for load on the image that automatically triggers the update.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM