开发者

Javascript Image.onload callback to object function

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, thi开发者_如何学JAVAs.posh);
            } catch(err) {
                console.log('Onload: could not draw image '+this.url);
                console.log(err);
            }
    };
}


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜