There are several questions about this in the forum, but I couldn't get a good answer for what I need.
I am getting into Canvas and Javascript, and I want to preload some images as soon as the game opens. I made an example of the method I wanted to build (and didn't work)
I have 3 files:
main.html where the canvas (there is only one in this example) is declared and I try to load an image, ImagePreloader.js where I preload all the images and Variables.js where I have my variables.
Could anyone please help me with this image preloading metod, or suggest me a viable one? I think the image is not loading because I am not using an onLoad() function, which I couldn't understand in the tutorials I read so far (I know how to apply it to an image, but not to an array of images)
main.html:
<!DOCTYPE HTML>
<html>
<body>
<canvas id=myCanvas width=800 height=600></canvas>
<script type=text/javascript src=Variables.js></script>
<script type=text/javascript src=ImagePreloader.js></script>
<script>
// Basic canvas info
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
// Draw one of the images. Somehow it doesn't work :(
context.drawImage(imageArray[3], x, y, width, height);
</script>
</body>
</html>
ImagePreloader.js
// This should preload the images in imageArray[i] with 0 <= i <= 5 ... right?
function preloader()
{
for(var i=0; i<5; i++)
{
imageArray[i].src=images[i];
}
}
Variables.js
// array of sources of my images
images = new Array();
images[0]=img1.jpg
images[1]=img2.jpg
images[2]=img3.jpg
images[3]=img4.jpg
images[4]=img5.jpg
// Stuff to draw the image
var x = 50;
var y = 50;
var width = 256;
var height = 256;
// Is this actually an array of images?
imageArray = new Image();
Thanks in advance!