1

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.

8
  • Where is ctx defined? Commented Sep 10, 2013 at 22:39
  • 1
    This probably doesn’t have anything to do with tooltip.icons, since there’s no error. Are you using the same image each time? If the image is cached, I don’t think onload is fired. Commented Sep 10, 2013 at 22:40
  • ctx is the canvas drawing context which is a global obtained using ctx = canvas.getContext("2d"); on the canvas DOM element. And no the images are different. Repeating the large block works, but I wanted to use the function to avoid repeating myself. Commented Sep 10, 2013 at 22:42
  • As @minitech suggested, it could be a problem of caching. Could you try using this line? `image.src = src + "?_" + (+new Date()); Commented Sep 10, 2013 at 22:48
  • 1
    Can you setup a simple fiddle? Commented Sep 10, 2013 at 22:56

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.