[英]Array of image canvas HTML5
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. 我正在尝试使用Canvas在HTML5中制作纸牌游戏,但是当我尝试在画布中心绘制3张纸牌时出现问题。
Error: 错误:
Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(HTMLImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap)'
未捕获到的TypeError:无法在'CanvasRenderingContext2D'上执行'drawImage':提供的值不是'(HTMLImageElement或HTMLVideoElement或HTMLCanvasElement或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 在哪里tableCard
for(var i=0; i<3; i++)
{
var cartaU = drawRandomCard();
tableCard.push(new Card(cartaU.Name, cartaU.semeTipo, cartaU.CardValue, cartaU.picture));
}
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. 现在,我注意到您的
x
和y
坐标也在闭包中引用。 This will also not work. 这也行不通。 You will need to store the x and y as attributes or data of the image element.
您将需要将x和y存储为图像元素的属性或数据。 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);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.