导入我的图像

时间:2012-07-09 15:01:59

标签: javascript html5 javascript-events html5-canvas

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

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);
    }
}
它不起作用!任何想法?

2 个答案:

答案 0 :(得分: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);
});

答案 1 :(得分: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

Preloading images with jQuery