I want to pre-load a directory of images into my canvas so that they are ready to be displayed when I need them.
I found this question on stackoverflow
and the accepted answer was extremely helpful.
Their function iterates through an array of image locations and then (i presume) pre-loads them to the canvas.
I am having difficulties actually displaying them once they are pre-loaded using this function. I'm well aware of the single image loading method of-
img = new Image();
img.src = imgLocation;
img.onload = function() {
context.drawImage(img, 0, 0);
}
but since they are already loaded, I am assuming I don't need to use img.onload
or any of the above code except for context.drawImage
to actually display the image.
When I try to load an image from the (what i can only assume is the out-putted array with all the images in it) i get a type error. when I check what's inside the array ( with a console.log()
) at any index it says [object, Object]
My code code looks like this:
var framesArr = new Array();
var framesAmnt = 300; // we would normally get this number from the PHP side of things
function ldBtn(){
//load all frames locations into framesArr
var i=0;
for (i=0;i<=(framesAmnt-1);i++){
framesArr[i] = "frames/Frame" + i + ".png";
}
//preload them
preloadImages(framesArr, preloadDone);
}
var deferreds = [];
var deferred;
function preloadImages (paths, callback) {
$.each(paths, function (i, src) {
deferred = $.Deferred(),
img = new Image();
deferreds.push(deferred);
img.onload = deferred.resolve;
img.src = src;
});
$.when.apply($, deferreds).then(callback);
}
function preloadDone(){
//any old index number will do. *Shruggs*
context.drawImage(deferreds[2], 0, 0); //this will cause a type error.
}
How can I display images onto the canvas that were loaded by the preloadImages
function?
I suppose I don't fully understand what happens when img = new Image();
img.src = imgLocation;
img.onload = function()
happens. What does javascript/jquery store the image as? if the answer is 'an object' then why won't it load the objects in this array?
Thank you in advance for any advice you can provide.