...

View Full Version : loading images into an array, then drawing to canvas



dreamcaster
03-23-2012, 03:34 PM
<html>
<head>
<title>test</title>
</head>
<body>
<script language = "javaScript">
var clouds = [];
var i = 0;
while(i <= 5) {
var cld = new Image();
cld.onload = function()
{
clouds.push(cld);
}
cld.src = "cloud.png";
i++;
}
document.write(clouds.length);
</script>
</body>
</html>


Where am I messing up clouds.length returns 0. Why?
I know this is simple, but it will get more complex. I can search for the code, but I would like feedback as to what I'm doing wrong. This is more than likely going to be a multi stage question. More to come...

------

Also, I would like to say that this is my first post. Thanks in advance to those who reply.

devnull69
03-23-2012, 04:06 PM
Image loading like that is an asynchronous task. The while loop will long be finished before even one of the onload handlers will be triggered. And only inside the onload handlers you change "clouds". Directly after the while loop, clouds.length is still 0 then.

Btw it doesn't make sense to me that you create 5 new images for only one "src".

dreamcaster
03-23-2012, 04:28 PM
Well, there are 6 different images, actually. The idea is to have a canvas in the BG and have clouds scrolling from either side. This is more of an example using the same technique.

Thanks for the thanks for the tip on the image loader.

The idea is to populate this array just to hold the clouds and select from it.

Next, have another array for 'active' clouds on the screen; this randomly selects maybe 12 clouds 6 on either side.

Now, maybe my question should be, how should I populate the first array?

dreamcaster
03-23-2012, 08:14 PM
Look, I don't need my hand held. Just need help loading the images into the first array. I'm pretty sure I can get the rest.

devnull69
03-24-2012, 08:47 AM
But you did that already with your first code (except that you need to change the "src" attribute for every new image) ... I don't understand the problem


var imageSrc = ["clowd1.png", "clowd2.png", "clowd3.png", "clowd4.png", "clowd5.png", "clowd6.png"];
var clouds = [];
var i = 0;
while(i <= 5) {
var cld = new Image();
cld.onload = function()
{
clouds.push(cld);
}
cld.src = imageSrc[i];
i++;
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum