Javascript图像onload函数从未被调用

javascript image onload function never called

本文关键字:调用 函数 图像 onload Javascript      更新时间:2023-09-26

我在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);         
        }       
    }
}

谢谢

Context #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");,而不执行new,则this将引用[object Window]

<<p> 解决方案/strong>

这取决于this的上下文。

  • bind
  • 或者通过声明和外部var _this = this;然后在onload中使用_this.loaded = true;

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