【发布时间】:2016-01-11 10:19:45
【问题描述】:
所以我一直在尝试让图像预加载器工作,因为我知道我需要先加载图像才能在画布上绘制它们。我遵循了这个描述:How do image preloaders work?,但我不确定如何将img.onload 变成一个方法,或者以某种方式制定解决方法,因为该函数无法访问它应该访问的变量。
这是我的代码。不包括 Canvas 类,因为它无关紧要。 提前致谢。
window.onload = function () {
var MyApp = new App();
MyApp.Initialize();
}
class App {
canvas: Canvas;
imageURLs: string[] = [];
images = [];
imagePreLoader: ImagePreLoader;
constructor() {
this.canvas = new Canvas(window.innerWidth, window.innerHeight, "mainCanvas");
this.ImagePreLoader = new ImagePreLoader(this.imageURLs, this.images);
}
Initialize() {
this.imageURLs.push("0.png");
this.imageURLs.push("1.png");
this.imagePreLoader.startLoadingAllImages(this.Loop.bind(this));
}
Loop() {
this.canvas.clear();
this.Draw();
requestAnimationFrame(this.Loop.bind(this));
}
Draw() {
for (var i = 0; i < this.images.length; i++) {
this.canvas.drawImage(this.images[i], i * 100, 100);
}
}
}
class ImagePreLoader {
imagesLoaded = 0;
imageURLs: string[];
images;
constructor(urlArray: string[], imageArray) {
this.imageURLs = urlArray;
this.images = imageArray;
}
startLoadingAllImages(callback): void {
for (var i = 0; i < this.imageURLs.length; i++) {
var img = new Image();
this.images.push(img);
img.onload = function () { //This doesn't work as the function can't access the variables of the class.
this.imagesLoaded++;
if (this.imagesLoaded >= this.imageURLs.length) {
callback();
}
}
img.src = this.imageURLs[i];
}
}
}
【问题讨论】:
标签: javascript oop canvas typescript