【问题标题】:image.onload into a methodimage.onload 到一个方法中
【发布时间】: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


    【解决方案1】:

    改变:

    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,即() =&gt; { ... },使this 关键字在这种情况下按预期工作。在这种情况下,function 将从调用者那里获得它的作用域 (this),给它一个错误的作用域。

    【讨论】:

    • 谢谢!这可行,但= function () 和= () =&gt; 之间有什么区别?
    • 您可以在这里阅读更多信息:typescriptlang.org/…
    • 漂亮。也简短而准确地解释了。谢谢
    猜你喜欢
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    • 2017-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    相关资源
    最近更新 更多