我的程序有问题 - " this.imageManager.get(" cowboy")"回馈" undefined"而且我不知道为什么。
1.有ImageMenager构造函数的代码
function ImageManager(placeholderDataUri) {
this._images = {};
if (placeholderDataUri) {
this._placeholder = new Image();
this._placeholder.src = placeholderDataUri;
}
}
_p = ImageManager.prototype;
_p.load = function(images, onDone, onProgress) {
// The images queue
var queue = [];
for (var im in images) {
queue.push({
key: im,
path: images[im]
});
}
if (queue.length == 0) {
onProgress && onProgress(0, 0, null, null, true);
onDone && onDone();
return;
}
var itemCounter = {
loaded: 0,
total: queue.length
};
for (var i = 0; i < queue.length; i++) {
this._loadItem(queue[i], itemCounter, onDone, onProgress);
}
};
_p._loadItem = function(queueItem, itemCounter, onDone, onProgress) {
var self = this;
var img = new Image();
img.onload = function() {
self._images[queueItem.key] = img;
self._onItemLoaded(queueItem, itemCounter, onDone, onProgress, true);
};
img.onerror = function() {
self._images[queueItem.key] = self._placeholder ? self._placeholder : null;
self._onItemLoaded(queueItem, itemCounter, onDone, onProgress, false);
};
img.src = queueItem.path;
};
_p._onItemLoaded = function(queueItem, itemCounter, onDone, onProgress, success) {
itemCounter.loaded++;
onProgress && onProgress(itemCounter.loaded, itemCounter.total, queueItem.key, queueItem.path, success);
if (itemCounter.loaded == itemCounter.total) {
onDone && onDone();
}
};
/**
* Returms the loaded image by the given value
* @param key image alias
*/
_p.get = function(key) {
return this._images[key];
};
2。有一个Renderer构造函数的代码
function Renderer() {
var self = this;
this.readyForDrawing = false;
//przygotowanie imageManager do pracy
this.imageManager = new ImageManager();
this.imageManager.load({
"cowboy": "cowboy.png"
}, this._change());
}
_p = Renderer.prototype;
_p.draw = function(ComponentObj) {
var object = ComponentObj;
alert(this.imageManager.get("cowboy")); //there is alert which display "undefined"
ctx.drawImage(this.imageManager.get("cowboy"), object.x, object.y, object.width, object.height);
};
_p._change = function() {
this.readyForDrawing = true;
};
当renderer.readyForDrawing具有true值但是发生错误时,我创建了对象渲染器和调用函数renderer.draw() -
未捕获的TypeError:无法执行&#39; drawImage&#39; on&#39; CanvasRenderingContext2D&#39;:提供的值不是&#39;(HTMLImageElement或HTMLVideoElement或HTMLCanvasElement或ImageBitmap)&#39;
this.imageManager.get("cowboy")
的值未定义且我不知道为什么(我正在使用函数ImageManager一段时间,一切都很好)。