2

This is driving me nuts - I have been round and round in circles, and this no joy. I am loading multiple dynamic images, and have a simple Javascript object which I instantiate for each image, and which has a callback to render the image once it has loaded asynchronously.

I have verified that the callback code works just fine on a stand-alone basis (ie. I can call the callback 'manually' after the image has loaded, and the image is rendered correctly), and I have verified that the image itself is successfully loaded (by switching the object's callback for a simple one line logging function), but when I try to tie it all together, the callback apparently never gets invoked.

I'm relatively new to JS and I suspect that I am missing something fundamental about the way functions within objects are defined, but despite a lot of Googling, can't work out what.

Please can someone show me the error of my ways?

function ImageHolder(aX,aY,aW,aH, anImageURL) {
    this.posx=aX;
    this.posy=aY;
    this.posw=aW;
    this.posh=aH;
    this.url=anImageURL;

    this.myImage = new Image();
    this.myImage.onload=this.onload;
    this.myImage.src=anImageURL;
    this.onload=function() {

        try {
            var d=document.getElementById("d");
            var mycanvas=d.getContext('2d');
            mycanvas.drawImage(this.myImage, this.posx, this.posy, this.posw, this.posh);
            } catch(err) {
                console.log('Onload: could not draw image '+this.url);
                console.log(err);
            }
    };
}

1 Answer 1

8

You have two problems: first, this.onload is not defined at the point at which you assign it to the image. You can fix this by missing out the stage of storing the onload handler function as a property of this. The second problem is that when the onload handler function is called, this is not set to what you think it is (in fact, it's a reference to the Image object that has just loaded). You need to store a reference to the current ImageHolder object and use it instead of this within the event handler function.

New code:

var that = this;

this.myImage = new Image();
this.myImage.onload=function() {
    try {
        var d=document.getElementById("d");
        var mycanvas=d.getContext('2d');
        mycanvas.drawImage(that.myImage, that.posx, that.posy, that.posw, that.posh);
    } catch(err) {
        console.log('Onload: could not draw image '+that.url);
        console.log(err);
    }
};
this.myImage.src = anImageURL;
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, thank you, THANK YOU. Now you point out the 'this' referencing, it all makes perfect sense.

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.