【问题标题】:Canvas image drawing order画布图像绘制顺序
【发布时间】:2013-07-02 11:44:25
【问题描述】:

我正在为等距游戏制作一个简单的引擎,以备将来使用。

问题是我在画布上绘图时遇到问题。以这段代码为例:

function pre_load() {
    var imgs = ['1', '1000','1010','1011','1012','1013'];
    var preload_image_object = new Image();
    $.each(imgs,function(i,c){
        preload_image_object.src='img/sprites/'+c.logo+'.png';
    })
}

function GameWorld() {
    //[...]
    this.render = function() {
        this.draw(1000, this.center);
        this.draw(1013, this.center);
        this.draw(1010, this.center);
    }

    this.draw = function(id, pixel_position) {
        draw_position_x = pixel_position[0] - this.tile_center[0];
        draw_position_y = pixel_position[1] - this.tile_center[1];

        inst = this;
        var img = new Image();
        img.onload = function () {
            inst.ctx.drawImage(img, draw_position_x, draw_position_y);
            console.log('Drawn: ' + id);
        }
        img.src = "img/sprites/"+id+".png";
    }

}

人们可能期望事物将按顺序绘制,id 1000,然后 id 1013,然后 id 1010,因为图像已经加载(即使没有,目前我正在本地服务器上工作)。

但是如果我多次刷新页面,我会得到不同的结果:

案例一

案例 2

案例 3

(可能发生任何其他排列)

我能想到的唯一解决方案是让函数“挂起”,直到调用了 onload 事件,然后才继续进行下一个 .draw() 调用。这是正确的方法吗?我该怎么做呢?有没有更好的解决方案?

谢谢!

【问题讨论】:

  • 你也可以使用回调方法,比如this.draw=function(id,pos,callback){...img.onload=function(){...callback.call();};

标签: javascript html canvas html5-canvas


【解决方案1】:

你的直觉是正确的......你需要一个图像加载器。

有很多图像加载器模式——这里有一个:

当你的所有图片都加载完毕后,下面的 imgs[] 数组会按照正确的顺序显示你的精灵。

var imgURLs = ['1', '1000','1010','1011','1012','1013'];
var imgs=[];
var imgCount=0;

function pre_load(){

    for(var i=0;i<imgURLs.length;i++){

        var img=new Image();
        imgs.push(img);
        img.onload=function(){
            if(++imgCount>=imgs.length){ 

                // imgs[] now contains all your images in imgURLs[] order

                render(); 

            }
        }
        img.src= "img/sprites/"+imgURLs[i]+".png";
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-06
    • 2012-10-08
    • 1970-01-01
    相关资源
    最近更新 更多