gpt4 book ai didi

javascript - image.onload 函数 - 为什么它不起作用?

转载 作者:行者123 更新时间:2023-11-30 13:07:16 25 4
gpt4 key购买 nike

我是 JS 新手。我想将关于一个对象的所有信息保存在一个地方。所以我做了这个功能:

function Obiekt(img) {
this.img = img;
this.ready = false;
this.image = new Image();
this.image.src = this.img;
this.image.onload = function() {
ready = true;
};
this.x = 0;
this.y = 0;
this.rotation = 0;
}

然后我创建了我的对象,命名为 hero。

var hero = new Obiekt("images/hero.png");

问题是,hero.ready 始终为 false,我无法绘制它。

if (hero.ready) {
ctx.drawImage(hero.image, 0, 0);
}

你能帮帮我吗?

最佳答案

两个问题:

  • 就绪找不到
  • 如果您的图像被缓存(取决于浏览器),您使用的顺序将不起作用,因为在您设置回调后图像未加载。

这是一个解决方案:

var _this = this;
this.image.onload = function() {
_this.ready = true;
};
this.image.src = this.img;

(我要补充一点,命名不是很好:我更喜欢 imgsrc 而不是 img)

关于javascript - image.onload 函数 - 为什么它不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15230138/

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