2012-09-21 30 views
3

如果圖表是由JSON數據創建的,所有有關如何動畫的示例都不會涵蓋。他們都使用靜態數據。 (請參閱Transition Animation。)從JSON動畫Google圖表

這是我通過JSON獲取數據的代碼。

<script type="text/javascript"> 
    google.load("visualization", "1", { packages: ["corechart"] }); 
    google.setOnLoadCallback(drawChart); 

    function drawChart() { 
     $.post('/Weight/WeightAreaChartData', {}, function (data) { 
      var tdata = new google.visualization.arrayToDataTable(data); 
      var options = { 
       title: 'Weight Lost & Gained This Month', 
       hAxis: { title: 'Day of Month', titleTextStyle: { color: '#1E4A08'} }, 
       vAxis: { title: 'Lbs.', titleTextStyle: { color: '#1E4A08' } }, 
       chartArea: { left: 50, top: 30, width: "75%" }, 
       colors: ['#FF8100'], 
       animation:{ 
        duration: 1000, 
        easing: 'in' 
       }, 
      }; 

      var chart = new google.visualization.AreaChart(
       document.getElementById('chart_div') 
      ); 

      chart.draw(tdata, options); 
     }); 
    } 
</script> 

我有一個按鈕,可以成功地重繪圖表。但是,它不生動。我怎樣才能讓圖表成爲動畫?感謝您的幫助。

$('#myBtn').click(function() { 
     drawChart(); 
}); 

回答

4

正如@FelipeFonseca躲避來,你每次#myBtn is clicked覆蓋圖。嘗試這樣做,而不是:

(function (global, undef) { 
    google.load("visualization", "1", { packages: ["corechart"] }); 
    google.setOnLoadCallback(drawChart); 

    var options = { 
     title: 'Weight Lost & Gained This Month', 
     hAxis: { title: 'Day of Month', titleTextStyle: { color: '#1E4A08'} }, 
     vAxis: { title: 'Lbs.', titleTextStyle: { color: '#1E4A08' } }, 
     chartArea: { left: 50, top: 30, width: "75%" }, 
     colors: ['#FF8100'], 
     animation:{ 
      duration: 1000, 
      easing: 'in' 
     } 
    }; 

    var chart; 
    function drawChart() { 
     $.post('/Weight/WeightAreaChartData', {}, function (data) { 
      var tdata = new google.visualization.arrayToDataTable(data); 

      if (!chart) { 
       chart = new google.visualization.AreaChart(
        document.getElementById('chart_div') 
       ); 
      } 

      chart.draw(tdata, options); 
     }); 
    } 

})(this); 
+0

我還沒有測試過,但我認爲你有。我已將其標記爲解決方案。 – user1477388

5

也許是因爲您每次創建圖表?

儘量讓chart一個全局變量,然後再試一次