2017-02-24 14 views
1

D3のアニメーションを開始、停止、再開するために1つのボタンを使用しています。D3、setIntervalとclearIntervalを使用したjavascript関数のスコープとイベントハンドラ

'animateTheMap'関数の中で、アニメーションを開始するにはsetIntervalに 'animateTimer'を割り当て、コールバック関数 'stopAnimateTheMap'を使用してアニメーションを停止するには、同じボタンにclickイベントを割り当てます。

ただし、stopAnimateTheMap関数は 'animateTimer'を表示できません。 "animateTimer"が定義されていません。

1)2つの関数をマージする必要がありますか?これを解決する方法がありますか? 2)複数の「クリック」イベントを同じボタンに追加して再生します。アニメーションを停止し、このイベントを処理するための最適な/適切な方法である私が最初にイベントごとに各変数を作成し、ボタンにそれらを割り当てられていた

は、1については

var animateMapButton = d3.select('body').append('button').attr({ 
             class: "button", 
             id: "animateMap"}) 
           .text("Animate the map") 

animateMapButton.on("click", animateTheMap) 

function animateTheMap(){ 
            animateMapButton.text("Stop the Animation") 
            animateMapButton.on('click',stopAnimateTheMap) 
            i=0;      

            var animateTimer = setInterval(function(){ 

             if(i<yearArray.length){ 
              i++; 
              d3.select('text.selected').classed('selected',false) 
              d3.select('#year'+yearArray[i]).classed('selected',true) 
              updateMapColor(yearArray[i]) 

              } 
             else{ 
              clearInterval(animateTimer) 
             } 
             },2500) 
          } 


function stopAnimateTheMap(){ 

            clearInterval(animateTimer)  
            animateMapButton.text("Animate the map")           
            animateMapButton.on("click",animateTheMap) 
           } 

答えて

1

をいただき、ありがとうございます)。?。:関数の外でanimateTimer変数を宣言するだけで済みます。

2)の場合:アニメーション化とアニメーション化を切り替えるクリックハンドラを使用します。

var animateMapButton = d3.select('body').append('button').attr({ 
     class: "button", 
     id: "animateMap"}) 
    .text("Animate the map") 

animateMapButton.on("click", toggleAnimating) 

var animateTimer; 
var isAnimating = false 

function toggleAnimating(){ 
    if (isAnimating) { 
     clearInterval(animateTimer)  
     animateMapButton.text("Animate the map")           
    } 
    else { 
     animateMapButton.text("Stop the Animation") 
     i=0;      

     animateTimer = setInterval(function(){ 

      if(i<yearArray.length){ 
       i++; 
       d3.select('text.selected').classed('selected',false) 
       d3.select('#year'+yearArray[i]).classed('selected',true) 
       updateMapColor(yearArray[i]) 

      } 
      else{ 
       clearInterval(animateTimer) 
      } 
     },2500) 
    } 

    isAnimating = !isAnimating; 
} 
関連する問題