Home > database >  Google chart animation is not visible when chart data is changed
Google chart animation is not visible when chart data is changed

Time:12-10

I am having trouble getting the Google chart animations to work properly. I think the problem is that the chart keeps getting redrawn instead of just the data updated, but I'm not sure how to remedy this based on Google's example code and my limited knowledge of JavaScript. I do not want to include a button to update the chart as the chart will eventually update data dynamically from a data source. How do I update my chart to properly display the animations on data change?

Reference: https://developers.google.com/chart/interactive/docs/animation

<!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>

CodePudding user response:

in order to animate the chart from one dataset to the next,
you need to keep a reference to the same chart.
instead of creating a new chart each time it is drawn.

see following example...

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);

note: google pie charts do not animate

  • Related