2014-10-14 2 views
0

중지 나는 떨어지고 상자의 애니메이션을 만들려면이 기능을 가지고 :은의 setTimeout 루프

function dropBox(y, width, height) { 
    var img_box = new Image(); 
    img_box.src = 'images/gift_box_small.png'; 

    var box_y_pos = y; 
    if(y==0) 
     box_y_pos = y-img_box.naturalHeight; 


    img_box.onload = function(){ 
     ctx_overlay.save(); 
     ctx_overlay.clearRect(0,0,width,height); 
     ctx_overlay.drawImage(img_box, (width/2)-(img_box.naturalWidth/2), box_y_pos); 
     ctx_overlay.restore(); 
    } 

    box_y_pos += 3; 

    var loopTimer = setTimeout(function() {dropBox(box_y_pos, width, height)},24); 
} 

나는 상자가 특정 Y 위치에 도달 및 기타 기능을 위해 호출 할 때 애니메이션을 중지합니다. setTimeout 선언 전에 Y 위치를 확인할 코드를 가질 수 없습니다. 아직 선언되지 않았기 때문에 setTimeout 선언에 도달 할 수 없으므로 이후에는 가질 수 없습니다. 그러면 어떻게 할 수 있습니까?

+0

당신이 바이올린을 제공 할 수 있습니까? – Alexandros

+1

'setTimeout' 호출을 조건으로 감싸기 만하면됩니까? 예 : '(y Yoshi

+0

@Alexandros 여기에 jsfiddle : http://jsfiddle.net/n2derqgw/ – Igal

답변

0

stop_y 위치의 추가 변수를 함수에 전달하십시오. 상자가 아직이 위치에 도달하지 않은 경우에만 그리고에서는 setTimeout()를 호출 :

function dropBox(y, width, height, stop_y) { 
     var img_box = new Image(); 
     img_box.src = 'http://corkeynet.com/test/images/gift_box_small.png'; 

     var box_y_pos = y; 
     if(y==0) 
      box_y_pos = y-img_box.naturalHeight; 


     img_box.onload = function(){ 
      ctx_overlay.save(); 
      ctx_overlay.clearRect(0,0,width,height); 
      ctx_overlay.drawImage(img_box, (width/2)-(img_box.naturalWidth/2), box_y_pos); 
      ctx_overlay.restore(); 
     } 

     box_y_pos += 3; 
     if (box_y_pos < stop_y) { 
      var loopTimer = setTimeout(function() {dropBox(box_y_pos, width, height, stop_y)},24); 
     } 
    } 

편집 여기에 코드 : http://jsfiddle.net/93jwqf2j/