Javascript图像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);
}
}
}
谢谢
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]
。
这取决于this
的上下文。
- 用
bind
- 或者通过声明和外部
var _this = this;
然后在onload
中使用_this.loaded = true;
。
代码:https://jsbin.com/pasumab/edit?js,控制台
相关文章:
- 如何从模块链中调用函数.导出到节点中
- 调用函数内部的函数
- 在javascript中调用c函数
- DropDownListFor赢得't在更改时调用函数
- Javascript页面调用函数
- 在动画结束之前调用函数
- 允许父窗口在其不同域的子iframe上调用函数
- 运行Infinite Scroll后调用函数时出现问题
- JavaScript:在调用函数的文本输入上按enter键
- 使用大括号和不使用bracs调用函数的区别
- javascript在事件上调用函数
- 从index.html调用函数,该函数无限循环
- 从带参数的字符串变量调用函数中的函数
- 为什么 JS 不在滚动时调用函数
- 是否可以在不更改上下文的情况下调用函数.apply
- 如何在ES6类中使用参数调用函数
- AngularJS:调用函数时编号不更新
- JavaScript中的立即调用函数表达式(IIFE)-传递jQuery
- 在JavaScript中调用函数时自定义此选项
- 调用函数中声明的变量