2012-08-23 4 views
2

캔버스가있는 애니메이션 배경을 실행하려고합니다. 현재 setTimeout은 크롬 Uncaught SyntaxError: Unexpected identifier에 오류를 표시합니다. 나는 그것을 잘못 움직여야 만한다.캔버스의 setTimeout

setTimeout을 삭제하고 tiles() 만 가지고도 모든 것이 정상적으로 작동합니다. 즉, 애니메이션이 적용되지 않지만 원하는 배경이 올바르게 표시됩니다. 그래서 나는 확실하다고 할 수 있습니다. setTimeout.

누구나 단서가 있습니까?

function createBackground(){   
     var canvas = document.createElement('canvas'), 
      ctx = canvas.getContext('2d'), 
      background = $('#game .background')[0], 
      rect = background.getBoundingClientRect(), //returns the dimension of background 
      gradient, 
      m = monster.settings.monsterSize; 

     canvas.width = rect.width; 
     canvas.height = rect.height; 

     /* create checker */ 
     tile_cols = canvas.width/m; 
     tile_rows = canvas.height/m; 

     setTimeout(tiles(ctx, m, tile_cols, tile_rows), 300); 

     /* add canvas to html element */ 
     background.appendChild(canvas); 
    } 

    function tiles(ctx, m, tile_cols, tile_rows){ 
     for (var i=0; i<tile_cols; i++){ 
      for (var j=0; j<tile_rows; j++){ 
       var x = Math.ceil(Math.random()*3); 

       switch(x){ 
        case 1: 
         ctx.fillStyle = 'black'; 
         break; 

        .... 

        case 3: 
         ctx.fillStyle = '#00080E'; 
         break; 
       } 

       ctx.strokeStyle = 'black'; 
       ctx.beginPath(); 
       ... 
       ctx.closePath(); 

       ctx.fill(); 
       ctx.stroke(); 

      }; 
     };  

     return this; 
    } 
+0

또한 함수에서 전역 개체를 불필요하게 반환하고 있습니다. 'tiles'는 생성자가 아니며 다른 상황을 강요하지 않기 때문에'this'는'window'를 가리키고 반환 될 필요가 없습니다. – Utkanos

+0

@Utkanos, 큰 충고, 고마워. –

답변

4

당신은이 작업에 대한 requestAnimationFrame 살펴해야

setTimeout(function() { 
    tiles(ctx, m, tile_cols, tile_rows) 
}, 300); 

setTimeout

변경 그것의 첫 번째 매개 변수에 tiles(ctx, m, tile_cols, tile_rows)의 결과를 할당하고 있습니다. Paul Irish는 그것에 대해 good article이라고 썼습니다.

+0

감사합니다. 좋은 기사 같아. –