Reputation: 1118
function render()
{
canvasBackground.drawImage(images[0], 0, canvas.height / 2, canvas.width, canvas.height / 2);
}
function initImages(paths)
{
requiredImages = paths.length;
for (i in paths)
{
var img = new Image();
img.src = paths[i];
images[i] = img;
images[i].onload = function ()
{
doneImages++;
}
}
}
function checkImages()
{
if (doneImages >= requiredImages)
{
loop();
}
else
{
setTimeout(function ()
{
checkImages();
}, 1);
}
}
initImages(["picture.png"]);
checkImages();
I did this exactly but nothing is showing up, any idea how to fix this?
Btw I didn't show you the loop functions which in turn runs the render function.
Upvotes: 1
Views: 865
Reputation: 105015
Here's a refactored version of your code.
It increments doneImages
until it's equal to paths.length
(at which point all the images are fully loaded).
Then render
is called on each image index.
BTW, your render function is distorting your images by stretching them. I assume that's intentional?
Example code and a Demo:
var canvas=document.getElementById("canvas");
var canvasBackground=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var images=[];
var paths=[];
paths.push('https://dl.dropboxusercontent.com/u/139992952/multple/animated.gif');
paths.push('https://dl.dropboxusercontent.com/u/139992952/multple/ball1.png');
initImages(paths);
function render(i)
{
canvasBackground.drawImage(images[i], 0, canvas.height / 2, canvas.width, canvas.height / 2);
}
function initImages(paths)
{
var doneImages=0;
for (i in paths)
{
var img = new Image();
img.src = paths[i];
images[i] = img;
images[i].onload = function ()
{
// just return if all the images aren't loaded yet
if(++doneImages<paths.length){return;}
for(var i=0;i<images.length;i++){ render(i); }
}
}
}
body{ background-color: ivory; }
#canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>
Upvotes: 1