2017-02-24 52 views
1

我正在使用一個按鈕來啓動,停止並恢復D3中的動畫。D3,帶有setInterval和clearInterval和事件處理程序的javascript函數範圍

在'animateTheMap'函數內部,我將setInterval分配給'animateTimer'以開始動畫,並將一個單擊事件附加到同一個按鈕以停止具有回調函數'stopAnimateTheMap'的動畫。

但是,stopAnimateTheMap函數看不到'animateTimer';因此拋出「animateTimer」沒有定義。

1)我需要合併兩個函數還是有辦法解決這個問題? 2)我添加多個'點擊'事件到同一個按鈕來播放和停止動畫這是一個最佳的/適當的方式來處理該事件我最初創建的每個事件每個變量,並將它們分配給按鈕

謝謝

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

爲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; 
} 
相關問題