【发布时间】: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