2017-07-17 69 views
0

我在下面的代碼中遇到了一些問題。這是我打電話給我開發的一個簡單遊戲上的一些資產上創建FadeIn和FadeOut動畫的函數,它使用了很好的CreateJS庫。我需要一次爲資產運行此代碼,然後在第一個功能完成時通過anohter資產運行它。功能如下:上一個函數完成之前執行的Javascript函數

function fadeInOut(asset, duration, stage) 
    { 
     stage.addChild(asset) 
     let fadeInOut = setInterval(function() 
     { 
     asset.alpha += 1/24; 
     if (asset.alpha >= 1) 
     { 
      asset.alpha = 1; 
      setTimeout(function() 
      { 
      let fadeOut = setInterval(function() 
      { 
       asset.alpha -= 1/24; 
       if (asset.alpha <= 0) 
       { 
       asset.alpha = 0; 
       stage.removeChild(asset); 
       clearInterval(fadeOut); 
       } 
      }, 1000/24) 
      }, 1000 * duration) 
      clearInterval(fadeInOut); 
     } 
     }, 1000/24) 
    } 

而且我調用這個函數的方式是這樣的:

fadeInOut(assets.eiko, 2, stage); 
    fadeInOut(assets.logo, 3, stage); 

我真的不明白爲什麼給函數的第二個呼叫同時與運行第一。

希望你能幫助我,因爲這對我來說是一個非常重要的項目。

預先感謝您。

+0

那怎麼JavaScript的工作......你的setInterval調用同時運行 - 你需要把你的第二個電話裏面最內層setInterval或其他......但如果你希望得到更好的幫助,你應該首先簡化問題。看看[mcve] –

+0

好的,非常感謝,我會研究一下。 –

+1

考慮使用TweenJS(或補間庫)淡入/淡出內容。 TweenJS有一個很棒的API來完成這樣的事情。 – Lanny

回答

0

恕我直言,你需要這樣的事情,我做了兩個方法例如:)

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="UTF-8"> 
<title>Example</title> 
<script src="https://code.createjs.com/createjs-2015.11.26.min.js"></script> 
<script> 
function init() 
{ 
    var stage = new createjs.Stage("canvas"); 
    createjs.Ticker.setFPS(24); //set some FPS 
    createjs.Ticker.addEventListener("tick", stage); //set autiomatic refresh 

    //draw some circles for the example usage 
    var circle1 = new createjs.Shape(); 
    circle1.graphics.beginFill("#FF0000").drawCircle(0,0,50); 
    circle1.x=100; 
    circle1.y=100; 
    circle1.alpha=0; 
    stage.addChild(circle1); 

    var circle2 = new createjs.Shape(); 
    circle2.graphics.beginFill("#0000FF").drawCircle(0,0,50); 
    circle2.x=300; 
    circle2.y=100; 
    circle2.alpha=0; 
    stage.addChild(circle2); 

    //first version with function call after the first animation 
    createjs.Tween.get(circle1).to({alpha:1},1000).to({alpha:0},1000).call(
     function() 
     { 
      createjs.Tween.get(circle2).to({alpha:1},1000).to({alpha:0},1000) 
     } 
    ); 

    //seconds version: with delay instead of onComplete function, comment first version above, uncomment code below and try 
    /* 
    createjs.Tween.get(circle1).to({alpha:1},1000).to({alpha:0},1000); 
    createjs.Tween.get(circle2).wait(2000).to({alpha:1},1000).to({alpha:0},1000) 
    */ 


} 
</script> 
</head> 
<body onload="init();"> 
    <canvas id="canvas" width="600" height="400"></canvas> 
</body> 
</html> 
相關問題