收藏
回答

如何制作一个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, 00this.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++;
}


这是为什么

回答关注问题邀请回答
收藏

1 个回答

  • Toxic_Obsidian
    Toxic_Obsidian
    2021-05-31

    最后那条setTimeout回调函数改成function(){ AiFemale.render(context); }就可以正常执行了,但在运行过程中怎么判断资源是否加载好呢?

    2021-05-31
    有用
    回复 1
    • Forever
      Forever
      2021-06-01
      没有加载好的图片就算调用了drawImage也不会绘制出来,同时也不会报错,运行过程中怎么判断资源是否加载好,传入一个回调函数进去,当onload或者onerror进行回调
      2021-06-01
      回复
登录 后发表内容