0

I'm trying to import all of my sources "images essentially" before starting my HTML5 game but I don't know how to do it! I tried this code but it doesn't work:

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();
}
});

and this is the oplach function:

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

but it doesn't work! Any idea?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Oussama Bouthouri
  • 615
  • 2
  • 8
  • 23

2 Answers2

0

Add the generated img tags to the DOM like this.

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);
});
Split Your Infinity
  • 4,159
  • 1
  • 21
  • 19
0

Create a hidden div and append all your images inside this div. When you need to use them inside your game they will be fully loaded and cached.

Something like this in your foreach loop.

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

Further reading

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

Preloading images with jQuery

Community
  • 1
  • 1
Undefined
  • 11,234
  • 5
  • 37
  • 62