动画

使用集合让一切井井有条 根据您的偏好保存内容并对其进行分类。

本页面介绍了如何为对图表所做的修改添加动画效果,而不是立即应用它们。

内容

概览

Google 图表可以通过以下两种方式之一顺畅地添加动画效果:在首次绘制图表时在启动时,或在更改数据或选项后重新绘制图表时。

如需在启动时呈现动画效果,请执行以下操作:

  1. 设置图表数据和选项。请务必设置动画时长和加/减速类型。
  2. 设置 animation: {"startup": true} - 在选项中设置此选项将使图表从在基线上绘制的系列值开始,并以动画形式呈现最终状态。
  3. 调用 chart.draw(),并传入您的数据和选项。

如需为过渡添加动画效果,请执行以下操作:

  1. 从已渲染的图表开始。
  2. 修改数据表格或选项。不同的图表类型支持不同的修改;请参阅支持的修改,了解哪些图表类型支持哪些修改。
  3. 使用 animation 选项指定过渡行为。
  4. 对图表调用 chart.draw() 以过渡到新值。

下面是一个简单的示例,它会在用户点击按钮时更改条形图中显示的单个值:

   function init() {
    var options = {
      width: 400,
      height: 240,
      animation:{
        duration: 1000,
        easing: 'out',
      },
      vAxis: {minValue:0, maxValue:1000}
    };
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'N');
    data.addColumn('number', 'Value');
    data.addRow(['V', 200]);

    var chart = new google.visualization.ColumnChart(
        document.getElementById('visualization'));
    var button = document.getElementById('b1');

    function drawChart() {
      // Disabling the button while the chart is drawing.
      button.disabled = true;
      google.visualization.events.addListener(chart, 'ready',
          function() {
            button.disabled = false;
          });
      chart.draw(data, options);
    }

    button.onclick = function() {
      var newValue = 1000 - data.getValue(0, 1);
      data.setValue(0, 1, newValue);
      drawChart();
    }
    drawChart();
  }

支持的修改

不同图表对不同类型的过渡的支持有所不同。不同类型的过渡包括:

  • 仅更改数据表值。行数和列数相同,且列保持其原始类型和角色。
  • 添加或移除列(系列)。
  • 添加或移除行(类别)。
  • 图表选项变更。目前,为变化添加动画效果的选项包括:
    • 视图窗口(vAxis.viewWindow.minvAxis.viewWindow.maxhAxis.viewWindow.minhAxis.viewWindow.max)- 更改视图窗口有助于实现“缩放”和连续的“偏移”效果(请参阅下面的示例)
    • vAxis.tickshAxis.ticks
    • vAxis.gridlines.counthAxis.gridlines.count
    • vAxis.directionhAxis.direction
    • vAxis.baselinehAxis.baseline
    • vAxis.logScalehAxis.logScale
    • 图表大小(heightwidth
    • 图表区域(chartArea.heightchartArea.widthchartArea.topchartArea.left
修改类型 有效的图表类型
值变更 ScatterChart、LineChart、AreaChart、BarChart、BubbleChart、ColumnChart、K 线图、SteppedAreaChart、ComboChart、Gauge
添加/移除行 散点图、折线图、面积图、气泡图、组合图(仅限折线图/面积图系列)
添加/移除列 散点图、折线图、面积图、条形图、气泡图、柱形图、K 线图、 阶梯面积图、组合图表
修改图表选项 散点图、折线图、面积图、条形图、气泡图、柱形图、K 线图、 阶梯面积图、组合图表

转换行为

名称
动画时长

动画的时长(以毫秒为单位)。如需了解详情,请参阅动画文档

类型:数字
默认:0
动画缓和

已应用于动画的加/减速函数。提供的选项如下:

  • “Linear”- 恒速。
  • “in”- 缓入 - 开始缓慢,加速。
  • “out”- 缓出 - 快速启动和减速。
  • “inAndOut”- 缓入和缓出 - 开始缓慢,加快,然后减慢。
类型:字符串
默认:“线性”
animation.startup

确定图表是否会在初始绘制时以动画形式呈现。如果为 true,则图表将从基线开始,并以动画方式呈现到最终状态。

类型:布尔值
默认 false

事件

绘制图表时,在为外部方法调用准备图表后会触发“ready”事件。转换完成后,图表将触发 animationfinish 事件。

名称
animationfinish

在过渡动画播放完毕时触发。

属性:无

示例

值变更

   // Some raw data (not necessarily accurate)
    var rowData1 = [['Month', 'Bolivia', 'Ecuador', 'Madagascar', 'Papua  Guinea',
                     'Rwanda', 'Average'],
                    ['2004/05', 165, 938, 522, 998, 450, 114.6],
                    ['2005/06', 135, 1120, 599, 1268, 288, 382],
                    ['2006/07', 157, 1167, 587, 807, 397, 623],
                    ['2007/08', 139, 1110, 615, 968, 215, 409.4],
                    ['2008/09', 136, 691, 629, 1026, 366, 569.6]];
    var rowData2 = [['Month', 'Bolivia', 'Ecuador', 'Madagascar', 'Papua  Guinea',
                     'Rwanda', 'Average'],
                    ['2004/05', 122, 638, 722, 998, 450, 614.6],
                    ['2005/06', 100, 1120, 899, 1268, 288, 682],
                    ['2006/07', 183, 167, 487, 207, 397, 623],
                    ['2007/08', 200, 510, 315, 1068, 215, 609.4],
                    ['2008/09', 123, 491, 829, 826, 366, 569.6]];

    // Create and populate the data tables.
    var data = [];
    data[0] = google.visualization.arrayToDataTable(rowData1);
    data[1] = google.visualization.arrayToDataTable(rowData2);

    var options = {
      width: 400,
      height: 240,
      vAxis: {title: "Cups"},
      hAxis: {title: "Month"},
      seriesType: "bars",
      series: {5: {type: "line"}},
      animation:{
        duration: 1000,
        easing: 'out'
      },
    };
    var current = 0;
    // Create and draw the visualization.
    var chart = new google.visualization.ComboChart(document.getElementById('visualization'));
    var button = document.getElementById('b1');
    function drawChart() {
      // Disabling the button while the chart is drawing.
      button.disabled = true;
      google.visualization.events.addListener(chart, 'ready',
          function() {
            button.disabled = false;
            button.value = 'Switch to ' + (current ? 'Tea' : 'Coffee');
          });
      options['title'] = 'Monthly ' + (current ? 'Coffee' : 'Tea') + ' Production by Country';

      chart.draw(data[current], options);
    }
    drawChart();

    button.onclick = function() {
      current = 1 - current;
      drawChart();
    }

添加和移除行

    var options = {
      width: 400,
      height: 240,
      vAxis: {minValue:0, maxValue:100},
      animation: {
        duration: 1000,
        easing: 'in'
      }
    };

    var chart = new google.visualization.LineChart(
        document.getElementById('visualization'));
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'x');
    data.addColumn('number', 'y');
    data.addRow(['100', 123]);
    data.addRow(['700', 17]);
    var button = document.getElementById('b1');
    function drawChart() {
      // Disabling the button while the chart is drawing.
      button.disabled = true;
      google.visualization.events.addListener(chart, 'ready',
          function() {
            button.disabled = false;
          });
      chart.draw(data, options);
    }

    button.onclick = function() {
      if (data.getNumberOfRows() > 5) {
        data.removeRow(Math.floor(Math.random() * data.getNumberOfRows()));
      }
      // Generating a random x, y pair and inserting it so rows are sorted.
      var x = Math.floor(Math.random() * 1000);
      var y = Math.floor(Math.random() * 100);
      var where = 0;
      while (where < data.getNumberOfRows() && parseInt(data.getValue(where, 0)) < x) {
        where++;
      }
      data.insertRows(where, [[x.toString(), y]]);
      drawChart();
    }
    drawChart();

添加和移除列

    var options = {
      width: 400,
      height: 240,
      vAxis: {minValue:0, maxValue:1000},
      animation: {
        duration: 1000,
        easing: 'out'
      }
    };

    var chart = new google.visualization.ColumnChart(
        document.getElementById('visualization'));
    var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz';
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'x');
    data.addColumn('number', 'A');
    data.addColumn('number', 'B');
    data.addRow(['A', 123, 40]);
    data.addRow(['B', 17, 20]);
    var addButton = document.getElementById('b1');
    var removeButton = document.getElementById('b2');
    function drawChart() {
      // Disabling the buttons while the chart is drawing.
      addButton.disabled = true;
      removeButton.disabled = true;
      google.visualization.events.addListener(chart, 'ready',
          function() {
            // Enabling only relevant buttons.
            addButton.disabled = (data.getNumberOfColumns() - 1) >= chars.length;
            removeButton.disabled = (data.getNumberOfColumns() - 1) < 2;
          });
      chart.draw(data, options);
    }
    function shuffleAndDrawChart() {
      for (var i = 0; i < data.getNumberOfRows(); ++i) {
        for (var j = 1; j < data.getNumberOfColumns(); ++j) {
          var num = Math.floor(Math.random() * 1000);
          data.setValue(i, j, num);
        }
      }
      drawChart();
    }
    addButton.onclick = function() {
      data.addColumn('number', chars[data.getNumberOfColumns() - 1]);
      shuffleAndDrawChart();
    }
    removeButton.onclick = function() {
      data.removeColumn(data.getNumberOfColumns() - 1);
      shuffleAndDrawChart();
    }
    drawChart();

更改视图窗口

    var options = {
      width: 400,
      height: 240,
      animation: {
        duration: 1000,
        easing: 'in'
      },
      hAxis: {viewWindow: {min:0, max:5}}
    };

    var chart = new google.visualization.SteppedAreaChart(
        document.getElementById('visualization'));
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'x');
    data.addColumn('number', 'y');
    var MAX = 10;
    for (var i = 0; i < MAX; ++i) {
      data.addRow([i.toString(), Math.floor(Math.random() * 100)]);
    }
    var prevButton = document.getElementById('b1');
    var nextButton = document.getElementById('b2');
    var changeZoomButton = document.getElementById('b3');
    function drawChart() {
      // Disabling the button while the chart is drawing.
      prevButton.disabled = true;
      nextButton.disabled = true;
      changeZoomButton.disabled = true;
      google.visualization.events.addListener(chart, 'ready',
          function() {
            prevButton.disabled = options.hAxis.viewWindow.min <= 0;
            nextButton.disabled = options.hAxis.viewWindow.max >= MAX;
            changeZoomButton.disabled = false;
          });
      chart.draw(data, options);
    }

    prevButton.onclick = function() {
      options.hAxis.viewWindow.min -= 1;
      options.hAxis.viewWindow.max -= 1;
      drawChart();
    }
    nextButton.onclick = function() {
      options.hAxis.viewWindow.min += 1;
      options.hAxis.viewWindow.max += 1;
      drawChart();
    }
    var zoomed = false;
    changeZoomButton.onclick = function() {
      if (zoomed) {
        options.hAxis.viewWindow.min = 0;
        options.hAxis.viewWindow.max = 5;
      } else {
        options.hAxis.viewWindow.min = 0;
        options.hAxis.viewWindow.max = MAX;
      }
      zoomed = !zoomed;
      drawChart();
    }
    drawChart();

更改图表大小

      google.charts.load('current', {'packages':['corechart']});
    google.charts.setOnLoadCallback(drawChart);

    function drawChart () {

      function genData () {
        var array = [];

        for (var i = 0; i < 10; i++) {
          var x = i,
              y = Math.floor(Math.random() * 50),
              z = Math.floor(Math.random() * 25);
          array.push([x, y, z]);
        }
        return array;
      }

      function doubleIt() {
        options.chartArea.height = '100%';
        options.chartArea.width = '100%';
      }

      function halveIt() {
        options.chartArea.height = '50%';
        options.chartArea.width = '50%';
      }

      function goTo50() {
        options.chartArea.left = '50%';
        options.chartArea.top = '50%';
      }

      function goTo10() {
        options.chartArea.left = '10%';
        options.chartArea.top = '10%';
      }

      var data = new google.visualization.DataTable();
      data.addColumn('number', 'X');
      data.addColumn('number', 'Y');
      data.addColumn('number', 'Z');

      data.addRows(genData());

      var options = {
        height: 500,
        chartArea: {
          height: '50%',
          width: '50%',
          top: '10%',
          left: '10%'
        },
        colors: ['#ee8100', '#9575cd'],
        animation: {
          duration: 1500,
          easing: 'linear',
          startup: true
        },
        vAxis: {
          ticks: [10, 20, 30, 40, 50, 60],
          gridlines: {color: '#ccc'}
        },
        hAxis: {
          ticks: [0, 4, 8, 12],
          gridlines: {color: '#ccc'}
        },
        legend: {position: 'none'},
        enableInteractivity: false
      };

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


      chart.draw(data, options);

      var btns = document.querySelector('#btns');
      btns.onclick = function (e) {
        switch(e.target.id) {
            case "size":
              options.chartArea.height === '50%' ? doubleIt() : halveIt();
              break;
            case "slide":
              options.chartArea.left === '10%' ? goTo50() : goTo10();
        }

        chart.draw(data, options);
      }

    }