Skip to content Skip to sidebar Skip to footer

A Function To Preload Images - Need To Draw Them Now, But How?

I'm dabbling with canvas. And I'm a little lost on something. I have this function: function preloadimages(arr) { var newimages = [] var arr = (typeof arr != 'objec

Solution 1:

This seems to be a complicated problem, but in reality isn't as bad as it looks. If you want to use pre-existing code, or just want to look at something for ideas you can have a look at: http://thinkpixellab.com/pxloader/ This library was used in the HTML5 version of Cut The Rope.

A simple custom implementation could be something like the following:

functionloadImages(arr, callback) {
    this.images = {};
    var loadedImageCount = 0;

    // Make sure arr is actually an array and any other error checkingfor (var i = 0; i < arr.length; i++){
        var img = newImage();
        img.onload = imageLoaded;
        img.src = arr[i];
        this.images[arr[i] = img;
    }

    functionimageLoaded(e) {
        loadedImageCount++;
        if (loadedImageCount >= arr.length) {
            callback();
        }
    }
}

And then you can call it like this:

var loader = loadImages(['path/to/img1', 'path/to/img2', 'path/to/img3'], function() {
    ctx.drawImage(loader.images['path/to/img1']); // This would draw image 1 after all the images have been loaded// Draw all of the loaded imagesfor (var i = 0; i < loader.images.length; i++) {
        ctx.drawImage(loader.images[i]);
    }
});

If you want more details on asset loading you can have a look at the asset loading section of Udacity's HTML5 Game Development course https://www.udacity.com/course/cs255

Solution 2:

A function I use:

functionImageLoader(sources, callback) 
{
    var images = {};
    var loadedImages = 0;
    var numImages = 0;

    // get num of sourcesfor (var src in sources) {
        numImages++;
    }

    for (var src in sources) {
        images[src] = newImage();
        images[src].onload = function() {

            if (++loadedImages >= numImages) {
                callback(images);
            }
        };
        images[src].src = sources[src];
    }
}

You call it like so:

var sources = {
    bg: path/to/img.png,
    title: path/to/img/png
};

var _images = {};
isReady = ImageLoader(sources, function(images) {
    _images = images;
});

And then to access your images

_images.bg;

Example:drawImage(_images.bg, 0, 0);

Post a Comment for "A Function To Preload Images - Need To Draw Them Now, But How?"