legaultmarc
legaultmarc

Reputation: 127

Function to automate image loading using canvas

In one of my projects, I successfully used the following code to render a png image in an html5 canvas using JavaScript.

var sizeIcon = new Image();
sizeIcon.draw = function() {
    ctx.drawImage(sizeIcon, tooltip.x + 10, tooltip.y + 10);
};

sizeIcon.onload = sizeIcon.draw;
sizeIcon.src = "./images/icons/ruler.png";
tooltip.icons.push(sizeIcon);

Since I have multiple icons to load, I implemented the following function:

var imageLoader = function(x, y, src) {
    var image = new Image();
    image.draw = function() {
        ctx.drawImage(image, x, y);
    };

    image.onload = image.draw;
    image.src = src;
    tooltip.icons.push(image);
};

imageLoader(tooltip.x + 10, tooltip.y + 10, "./images/icons/ruler.png");

With tooltip.icons being a globally accessible array. This function does nothing (and does not produce any error nor warnings in the console). I also tried filling the tooltip.icons array directly using something like tooltip.icons[n] = new Image(); without success (where n = tooltip.icons.length). There is probably a part of the JavaScript scope that I don't understand.

Upvotes: 1

Views: 294

Answers (1)

user1693593
user1693593

Reputation:

You are basically risking invalidating your image object (as in not available) when you get to the callback handler as image loading is asynchronous and the function will (most likely) exit before the onload is called.

Try to do a little switch around such as this:

var imageLoader = function(x, y, src) {

    var image = new Image();

    function draw() {
        // use *this* here instead of image
        ctx.drawImage(this, x, y)
    };

    image.onload = draw;
    image.src = src;

    tooltip.icons.push(image);
};

Instead of the small hack here you could store the coordinates (and urls) in an array and iterate through that.

Upvotes: 1

Related Questions