0

在开始我的 HTML5 游戏之前,我试图导入我所有的源“基本上是图像”,但我不知道该怎么做!我尝试了这段代码,但它不起作用:

var canvas = document.getElementById('stage');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
canvas.style.background = 'url(img/tapis.jpg)';
var ctx = canvas.getContext('2d');

var carta = ["img/a1.png","img/a2.png","img/a3.png","img/a4.png","img/a5.png","img/a6.png","img/a7.png",
             "img/a8.png","img/a9.png","img/a10.png",
             "img/b1.png","img/b2.png","img/b3.png","img/b4.png","img/b5.png","img/b6.png","img/b7.png",
             "img/b8.png","img/b9.png","img/b10.png",
             "img/c1.png","img/c2.png","img/c3.png","img/c4.png","img/c5.png","img/c6.png","img/c7.png",
             "img/c8.png","img/c9.png","img/c10.png",
             "img/d1.png","img/d2.png","img/d3.png","img/d4.png","img/d5.png","img/d6.png","img/d7.png",
             "img/d8.png","img/d9.png","img/d10.png"];

var n = carta.length;
carta.forEach(function(srcu) {
var img = new Image();
img.src = srcu;
img.onload = function () {
    --n || oplach();
}
});

这是 oplach 函数:

function oplach(){
    var image = new Image();
    for(var i=0; i<carta.length; i++)
    {
        image.src= carta[i];
        ctx.drawImage(image,(i*40),50);
    }
}

但它不起作用!任何想法?

4

2 回答 2

0

创建一个隐藏的 div 并将所有图像附加到此 div 中。当您需要在游戏中使用它们时,它们将被完全加载和缓存。

在你的 foreach 循环中有这样的东西。

var img = document.createElement("img");
img.src = yoursrc;
document.getElementById("hiddenelement").appendChild(img);

进一步阅读

http://www.mediacollege.com/internet/javascript/image/preload.html

使用 jQuery 预加载图像

于 2012-07-09T15:07:43.620 回答
0

像这样将生成的 img 标签添加到 DOM 中。

carta.forEach(function(srcu) {
  var img = new Image();
  img.src = srcu;
  img.onload = function () { --n || oplach(); }

  // ADD THE FOLLOWING LINE TO YOUR CODE
  document.documentElement.appendChild(img);
});
于 2012-07-09T15:05:57.680 回答