如何制作一个Image管理类?
教程上说使用wx.createImage之后可以通过设置onload回调函数的方式进行下一步,所以我做了一个类,大概逻辑是这样的: export class ViewObject{
anchor = {
x : 0,
y : 0
};
coord = {
x : 0,
y : 0
};
size = {
x : 0,
y : 0
};
texture = {
resource : null,
fit_to_size : true,
prepared : false,
errmsg : null
};
behavior = {
onload : null,
onupdate : null,
ondestroy : null
};
z_order = 0;
visibility = true;
alpha = 1.0;
rotate_deg = 0.0;
constructor(res_path, x, y){
this.texture.prepared = false;
this.texture.resource = wx.createImage();
this.texture.resource.caller = this;
this.texture.resource.onload = function(){
this.caller.set_prepared();
};
this.texture.resource.onerror = function(){
this.caller.set_loaderr();
};
this.texture.resource.src = res_path;
this.coord.x = x;
this.coord.y = y;
}
set_prepared(){
this.size.x = this.texture.resource.width;
this.size.y = this.texture.resource.height;
this.texture.prepared = true;
if(this.behavior.onload) this.behavior.onload();
}
set_loaderr(msg){
this.texture.errmsg = msg;
console.log('Error occurred.');
}
// ...
render(context){
if(!this.texture.prepared) return false;
if(!this.visibility) return true;
context.save();
if(this.alpha != 1.0) context.globalAlpha = this.alpha;
context.translate(this.coord.x - this.anchor.x, this.coord.y - this.anchor.y);
context.rotate(this.rotate_deg * Math.PI / 180.0);
context.drawImage(this.texture.resource, 0, 0, this.size.x, this.size.y);
context.restore();
return true;
}
};
然后问题就来了,如果我定义一个AiFemale = new ViewObject('img/AiFemale.png', 100, 100);然后使用 AiFemale.behavior.onload = function(){ AiFemale.render(context);} // 这里的context是一个2d的上下文
就能正常地画出图片,但如果我用下面的方式: let flag = false;
while(!flag){
flag = AiFemale.render(context); // 在没有prepare好的状态下,会直接返回false
}
然后它就会卡死,加入setTimeout()也一样。 let i = 0;
while(i < 100){
setTimeout(AiFemale.render(context), 500);
i++;
}
这是为什么