VacAng
VacAng

Reputation: 13

javascript image onload function never called

I'm having a problem while loading pictures in my javascript. Seems that the .onload function is never called and so the picture is not marked as loaded. Can you help?

Here is the code:

//image loader
var img = function (source){
    this.loaded = false;
    this.image = new Image();
    this.image.onload = function () {
        this.loaded = true;
    };
    this.image.src = source;            
}

//default component definition
var component = function (x, y){
    this.x = x;
    this.y = y;
    this.draw = function (offsetX, offsetY, img){
        if(img.loaded){         
            ctx.drawImage(img.image, 
            this.x + offsetX, 
            this.y + offsetY,
            img.image.width, img.image.height);         
        }       
    }
}

Thanks

Upvotes: 0

Views: 893

Answers (1)

Șerban Ghiță
Șerban Ghiță

Reputation: 1967

Context #1

this.image.onload = function () {
    this.loaded = true;
};

this referes to [object HTMLImageElement], not to the img instance.

Context #2

Now, changing the code to:

this.image.onload = function () {
    this.loaded = true;
}.bind(this);

When you do new img("http://serban.ghita.org/imgs/serban.jpg");, this will refer to your [object Object].

Context #3

Now, If you do img("http://serban.ghita.org/imgs/serban.jpg");, without new, this will refer to [object Window].

Solution

It depends on the context of this.

  • You change it with bind
  • Or by declaring and external var _this = this; and then use _this.loaded = true; inside onload.

Code: https://jsbin.com/pasumab/edit?js,console

Upvotes: 2

Related Questions