애니메이션

이 페이지에서는 차트의 수정사항을 즉시 적용하는 대신 애니메이션으로 표시하는 방법을 설명합니다.

목차

개요

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.min, vAxis.viewWindow.max, hAxis.viewWindow.min, hAxis.viewWindow.max) - 뷰 창을 변경하면 '확대/축소' 및 연속적인 '드리프트' 효과를 달성하는 데 유용합니다 (아래 예 참조).
    • vAxis.tickshAxis.ticks
    • vAxis.gridlines.counthAxis.gridlines.count
    • vAxis.directionhAxis.direction
    • vAxis.baselinehAxis.baseline
    • vAxis.logScalehAxis.logScale
    • 차트 크기 (heightwidth)
    • 차트 영역 (chartArea.height, chartArea.width, chartArea.top, chartArea.left)
수정 유형 유효한 차트 유형
값 변경 분산형 차트, 선 차트, AreaChart, 막대 그래프, BubbleChart, ColumnChart, CandlestickChart, SteppedAreaChart, 콤보차트, 게이지
행 추가/삭제 분산형 차트, 선 차트, 영역 차트, 풍선형 차트, 콤보 차트 (선/영역 계열만 해당)
열 추가/삭제 분산형 차트, 선 차트, AreaChart, 막대 그래프, BubbleChart, ColumnChart, CandlestickChart, SteppedAreaChart, ComboChart
차트 옵션 수정 분산형 차트, 선 차트, AreaChart, 막대 그래프, BubbleChart, ColumnChart, CandlestickChart, SteppedAreaChart, ComboChart

전환 동작

이름
animation.duration

애니메이션 재생 시간(밀리초)입니다. 자세한 내용은 애니메이션 문서를 참고하세요.

유형: 숫자
기본값: 0
animation.easing

애니메이션에 적용된 이징 함수입니다. 사용할 수 있는 옵션은 다음과 같습니다.

  • 'linear' - 일정한 속도.
  • 'in' - Ease in - 천천히 시작하여 속도를 높입니다.
  • 'out' - Ease out - 빠르게 시작하고 느려집니다.
  • 'inAndOut' - 이즈 인/아웃 - 천천히 시작한 다음 속도를 높인 다음 낮춥니다.
유형: 문자열
기본값: 'linear'
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);
     
}

   
}