搜尋

首頁  >  問答  >  主體

Google圖表動畫在圖表資料變化時失去可視性

<p>我在使Google圖表動畫正常工作方面遇到了麻煩。我認為問題在於圖表不斷重繪而不僅僅是更新數據,但是基於Google的範例程式碼和我有限的JavaScript知識,我不確定如何解決這個問題。我不想包含一個按鈕來更新圖表,因為圖表最終將從資料來源動態更新資料。如何更新我的圖表以正確顯示數據變化的動畫? </p> <p>參考:https://developers.google.com/chart/interactive/docs/animation</p> <pre class="brush:php;toolbar:false;"><!DOCTYPE html> <html> <head> <base target="_top"> <script src="https://www.gstatic.com/charts/loader.js"></script> </head> <body> <div id="pizzaChart" style="overflow: hidden"></div> <p id="logger"></p> <script> google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var mushroomData = Math.floor(Math.random() * 11); document.getElementById("logger").innerHTML = mushroomData; var data = new google.visualization.DataTable(); data.addColumn('string', 'Topping'); data.addColumn('number', 'Slices'); data.addRows([ ['Mushrooms', mushroomData], ['Onions', 1], ['Olives', 1], ['Zucchini', 1], ['Pepperoni', 2] ]); var options = { title: 'How Much Pizza I Ate Last Night', width: '100%', animation: {duration: 1000, easing: 'out'} }; var chart = new google.visualization.ColumnChart(document.getElementById('pizzaChart')); chart.draw(data, options); } setInterval(drawChart, 1000); </script> </body> </html></pre>
P粉170438285P粉170438285453 天前733

全部回覆(1)我來回復

  • P粉301523298

    P粉3015232982023-09-03 09:22:36

    為了讓圖表從一個資料集動畫到下一個資料集,您需要保留對相同圖表的引用,而不是每次繪製時建立新的圖表。

    請參考以下範例...

    google.charts.load('current', {'packages':['corechart']});
    google.charts.setOnLoadCallback(initChart);
    var chart;
    
    function initChart() {
      chart = new google.visualization.ColumnChart(document.getElementById('pizzaChart'));
      drawChart();
    }
    
    function drawChart() {
    
      var mushroomData = Math.floor(Math.random() * 11);
      document.getElementById("logger").innerHTML = mushroomData;
    
      var data = new google.visualization.DataTable();
      data.addColumn('string', 'Topping');
      data.addColumn('number', 'Slices');
      data.addRows([
        ['Mushrooms', mushroomData],
        ['Onions', 1],
        ['Olives', 1],
        ['Zucchini', 1],
        ['Pepperoni', 2]
      ]);
    
      var options = {
        title: 'How Much Pizza I Ate Last Night',
        width: '100%',
        animation: {duration: 1000, easing: 'out'}
      };
    
      chart.draw(data, options);
    }
    
    setInterval(drawChart, 1000);

    注意:Google圓餅圖不支援動畫效果。

    回覆
    0
  • 取消回覆