簡體   English   中英

javascript image onload函數從未調用

[英]javascript image onload function never called

在javascript中加載圖片時遇到問題。 似乎從未調用.onload函數,因此該圖片未標記為已加載。 你能幫我嗎?

這是代碼:

//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);         
        }       
    }
}

謝謝

上下文1

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

this[object HTMLImageElement] ,而不是img實例。

上下文2

現在,將代碼更改為:

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

當您執行new img("http://serban.ghita.org/imgs/serban.jpg"); this將引用您的[object Object]

上下文#3

現在,如果您執行img("http://serban.ghita.org/imgs/serban.jpg"); ,沒有newthis將是指[object Window]

這取決於上下文this

  • 你用bind改變它
  • 或者通過聲明和外部var _this = this; 然后使用_this.loaded = true; 內部onload

代碼: https//jsbin.com/pasumab/edit?js,控制台

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM