0

I'm trying to make a card game in HTML5 with Canvas, but I have a problem when I try to draw 3 card at center of my canvas.

Error:

Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(HTMLImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap)'

My Code:

if (tableCard.length > 0)
{
    var x = 0;
    var y = 180;
    var tableImage = [];
    for (var i = 0; i < tableCard.length; i++)
    {                                                
        tableImage[i] = new Image();

        tableImage[i].onload = function () {                            
            context.drawImage(tableImage[i], x, y);
        };
        x = +90;
        carterimanenti = deckOfCard.length;
        tableImage[i].src = tableCard[i].picture;
    }
}

where tableCard

for(var i=0; i<3; i++)
{
    var cartaU = drawRandomCard();
    tableCard.push(new Card(cartaU.Name, cartaU.semeTipo, cartaU.CardValue, cartaU.picture));
}
CubeJockey
  • 2,209
  • 8
  • 24
  • 31
Dario9494
  • 29
  • 6
  • Possible duplicate of [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Scimonster Jan 11 '16 at 16:55

1 Answers1

0

You are trying to refer to an indexing variable in a callback. When the callback is executed this variable's value is out of bounds of your array:

context.drawImage(tableImage[**i**], x, y);

You will need to extract the applicable image element in another way:

tableImage[i].onload = function (event) {
    context.drawImage(event.target, x, y);
};

Now I notice that your x and y coordinates are also referenced in the closure. This will also not work. You will need to store the x and y as attributes or data of the image element. You can do something like this:

var image = tableImage[i];
image.setAttribute("data-x", x);
image.setAttribute("data-y", y);
tableImage[i].onload = function () {
    var image = event.target,
        x = parseInt(image.getAttribute("data-x", 10),
        y = parseInt(image.getAttribute("data-y", 10);                          
    context.drawImage(image, x, y);
};
Konstantin Dinev
  • 34,219
  • 14
  • 75
  • 100
  • Hi! Thanks alot you fixed my error, but how and where i need to store the X and Y attributes? Sorry i'm a student ! – Dario9494 Jan 11 '16 at 17:36