我正在为等距游戏制作一个简单的引擎以供将来使用。
问题是我在 Canvas 上绘图时遇到问题。以这段代码为例:
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 的顺序绘制,因为图像已经加载(即使没有,目前我正在本地服务器上工作)。
但是如果我多次刷新页面,我会得到不同的结果:
案例1
案例2
案例3
(可能会发生任何其他排列)
我能想到的唯一解决方案是使函数“挂起”,直到调用 onload 事件,然后才继续进行下一个 .draw() 调用。这是正确的方法吗?我该怎么做呢?有更好的解决办法吗?
谢谢!
最佳答案
你的直觉是正确的......你需要一个图像加载器。
有很多图像加载器模式 - 这是一个:
当所有图像完全加载后,下面的 imgs[] 数组将按正确的顺序排列 Sprite 。
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";
}
}
关于javascript - Canvas图像绘制顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17416706/