画布图像绘制顺序 [英] Canvas image drawing order

查看:46
本文介绍了画布图像绘制顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm making a simple engine for isometric games to use in the future.

问题是我在画布上绘画时遇到麻烦.以下面的代码为例:

The thing is i'm having trouble drawing on the canvas. Take for instance this code:

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.

One might expect that things will be drawn in the order, id 1000, then id 1013, then id 1010 since the images are already loaded(even if not, currently i'm working on a local server).

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

But if I refresh the page several times, I'll get different results:

案例1

案例2

案例3

(可能还会发生其他排列)

(Any other permutation may happen)

我能想到的唯一解决方案是使函数挂起",直到调用onload事件为止,然后再进行下一个.draw()调用.这是正确的方法吗?我将如何去做呢?有更好的解决方案吗?

The only solution I can think about is making the function "hang" until the onload event has been called and only then proceed to the next .draw() call. Would this be the right approach? How would I go about doing it? Is there a better solution?

谢谢!

推荐答案

您的直觉是正确的……您需要图像加载器.

Your intuition is correct...you need an image loader.

有很多图像加载器模式-这是一个:

There are plenty of image loader patterns out there--here's one:

当所有图像全部加载完毕后,下面的imgs []数组会将您的精灵按适当的顺序放置.

When all your images are fully loaded, the imgs[] array below has your sprites in proper order.

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";
    }

}

这篇关于画布图像绘制顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆