【发布时间】:2011-09-08 02:33:05
【问题描述】:
尝试使用 Image() 对象执行 .onload 方法,但显然它没有继承其函数中的“this”。有什么帮助吗?
function UI() {
this.canvas_obj = document.getElementById('game');
this.canvas = this.canvas_obj.getContext('2d');
this.imgcache = {};
this.imglist = [
'rooms/main-square.png'
];
for (var i = 0; i < this.imglist.length ; i++) {
var img = new Image();
img.src = this.imglist[i];
this.imgcache[this.imglist[i]] = img;
}
}
// snip //
/*
* drawImg
* Draws an image on the canvas at the specified x, y (if the image isn't in the pre-cache, it creates it as well)
* @param str image path
* @param array x,y
* @param array width, height
*/
UI.prototype.drawImg = function(path, coords, size) {
var found = false;
if (size == undefined) {
var w = 0;
var h = 0;
} else {
var w = size[0];
var h = size[1];
}
for (var i = 0; i < this.imgcache.length ; i++) {
if (path == this.imgcache[i].src) {
found = true;
}
}
if (!found) {
var img = new Image();
img.src = path;
this.imgcache[path] = img;
}
if (w == 0 && h == 0) {
this.imgcache[path].onload = function() {
this.canvas.drawImage(this.imgcache[path], coords[0], coords[1], this.imgcache[path].width, this.imgcache[path].height);
};
} else {
this.imgcache[path].onload = function() {
this.canvas.drawImage(this.imgcache[path], coords[0], coords[1], w, h);
};
}
}
【问题讨论】:
-
代码中的另一点。如果您希望始终为图像调用 onload,则必须在设置
.src之前设置 onload 处理程序,因为如果图像来自浏览器缓存,则在设置.srv时 onload 可能会立即触发。跨度>
标签: javascript canvas prototype-programming