JavaScript Failed to execute 'drawImage'
Asked Answered
H

3

36

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].

Hyrcania answered 15/3, 2014 at 22:39 Comment(3)
Have you checked that all your image elements have finished loading before you try to draw them?Electroform
@Electroform Well I just editted it so that the images were all visible in the .html, but for some reason it doesn't show up there as well. Is there a limit on the amount of <img> that can be loaded in a .html file? You can see all the loaded images here: JSFiddleHyrcania
I got this error because I was trying to load a corrupted image.Hydrograph
H
49

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

Hyrcania answered 15/3, 2014 at 23:9 Comment(0)
B
4

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

window.onload=function(){
       board.drawImage(document.getElementById("player_explode"), this.x, this.y);
}
Boccioni answered 25/9, 2014 at 2:55 Comment(0)
R
4

For people in 2021 learning React, you have to call the context.drawImage() in the img.onload or nothing will be shown on the canvas! Here is a real world working example:

useEffect(() => {
    canvasRef.current.width = mapXYWH.w * UNIT
    canvasRef.current.height = mapXYWH.h * UNIT
    const context = canvasRef.current.getContext("2d")

    map.map(o => {
        const img = new Image(o.width*UNIT,o.height*UNIT)
        img.src = o.normal
        img.onload = () =>
            context.drawImage(img, (o.x-mapXYWH.x)*UNIT, (o.y-mapXYWH.y)*UNIT)
    })
}, [map, mapXYWH])

See also: React -- Canvas Won't Draw Image

Rachaba answered 4/6, 2021 at 7:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.