JavaScript Failed to execute 'drawImage'

2019-01-23 11:27发布

问题:

Ok so I'm creating a game with JavaScript Canvas Elements and such. I've been able to load in TONS of Images, but on a select few, JavaScript replies with Errors such as

Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': No function was found that matched the signature provided.

Which makes NO SENSE at all, because the same code works in other places!?!

Here is an example I have in my code:

board.drawImage(document.getElementById("player_explode"), this.x, this.y);

Inside of an objects method, Player.die(), respectively.

Does anyone know why this behaviour is coming about? I'm getting very frustrated about it...

Here is a JSFiddle to demonstrate, alonside all the code. Player.die() is located on line[242].

回答1:

The problem was the way that I was loading my Images, I should've been doing:

var image = new Image();
image.src = "imagesource.jpg";

But instead I was get the elements by id from the document page.

Resources:

Explanation on loading images

Explanation on how html loads images



回答2:

you should wait all elements load,so do like this:

window.onload=function(){
       board.drawImage(document.getElementById("player_explode"), this.x, this.y);
}