【问题标题】:Google pie chart animation of the slices colors切片颜色的谷歌饼图动画
【发布时间】:2019-04-28 12:29:38
【问题描述】:

我有一个 Google 饼图,我尝试使用简单的 JavaScript 代码制作动画。

我想改变我的馅饼的颜色。为什么我的代码不起作用?

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

function drawChart() {
  var data1 = google.visualization.arrayToDataTable([
  ['Task', 'Hours per Day'],
  ['A1', 0],
  ['Failed',1],
  ['A2', 0],
  ['Passed', 3],     
]);

 var colors1 = ['#ef7777', '#ef7777', '#b2d284', '#b2d284', '#f6c7b6'];
 var colors2 =  ['#ff00ff', '#ff00ff', '#02d2ff', '#02d2ff', '#f6c7b6'];
 var colors3 = colors2;

var options1 = {'title':'Logic', 'width':'50%', 'height':'50%', legend:{position:'none'}, 'is3D':true,  
chartArea: {width: '70%', height: '70%'},  
colors: colors3,    
    'backgroundColor': '#fef7f8',
    pieSliceTextStyle: {
            color: '#000000',
            bold: true,
            fontSize:16
        }
  }; 

var chart1 = new google.visualization.PieChart(document.getElementById('piechart1')); 

  chart1.draw(data1, options1);
  var percent = 0;
        var handler = setInterval(function(){
            // values increment
            percent += 1;
            if (percent%2 == 1) {
            colors3 = colors1;
            }
            else
            {
            colors3 = colors2;
            }
            chart1.draw(data1, options1);

            if (percent > 74)

                clearInterval(handler);
        }, 333);  
}

所以,我在这里为我的饼图设置了 2 个带有颜色集的数组。第一个有红色和绿色,第二个有蓝色和紫色。

我希望使用“setInterval”函数在这些颜色集之间连续切换。

【问题讨论】:

  • 你有什么问题?
  • 为什么我的代码不起作用?如何通过更改饼图颜色来制作饼图动画...?

标签: javascript animation google-visualization


【解决方案1】:

colorsoptions 对象的键。您的 setInterval 调用的回调函数更改了一个名为 colors3 的变量,但您没有将它分配给原始对象,因此它永远不会被使用。

    if (percent % 2 == 1) {
      colors3 = colors1;
    } else {
      colors3 = colors2;
    }
    options1.colors = colors3; // here we're assigning it!
    chart1.draw(data1, options1);

【讨论】: