gpt4 book ai didi

javascript - image.onload 到方法中

转载 作者:搜寻专家 更新时间:2023-10-30 21:43:00 25 4
gpt4 key购买 nike

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

最佳答案

改变:

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 关键字在这种情况下按预期工作。在这种情况下,函数 将从调用者那里获得它的作用域 (this),从而给它一个错误的作用域。

关于javascript - image.onload 到方法中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34256916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com