image.onload成一个方法

时间:2015-12-13 22:01:52

标签: javascript oop canvas typescript

所以我一直试图让图像预加载器工作,因为我已经知道我需要加载图像才能在画布上绘制它们。我已经遵循了这个描述: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];
            }
        }
    }

1 个答案:

答案 0 :(得分:2)

更改:

img.onload = function () { //This doesn't work as the function can't access the variables of the class.
    this.imagesLoaded++;
    if (this.imagesLoaded >= imageURLs.length) {
        callback();
    }
}

到:

img.onload = () => { 
    this.imagesLoaded++;
    if (this.imagesLoaded >= imageURLs.length) {
        callback();
    }
}

使用lambda,即() => { ... },可使this关键字在此情况下按预期工作。 function将从调用者获取其范围(this),在这种情况下会给它一个错误的范围。