2013-07-02 3 views
1

앞으로 사용할 등각 투상 게임을위한 간단한 엔진을 만들고 있습니다.캔버스 이미지 그리기 순서

캔버스에 그리는 데 문제가 있습니다.

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

1

사례 2

2

사례 3

3

내가 생각할 수있는 유일한 해결책은 onload 이벤트가 호출 만 그 다음 .draw로 진행 될 때까지 함수가 "중지"하고있다

) (전화를 (다른 순열가 발생할 수 있습니다) . 이것이 올바른 접근 방법일까요? 그 일을 내가 어떻게 할까? 더 나은 해결책이 있습니까?

감사합니다.

+0

, this.draw = 기능 (아이디, POS, 콜백)'같은 {... img.onload = 함수() {... callback.call();} ;' – Passerby

답변

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

} 
또한 콜백 방법을 사용할 수 있습니다