单独为数据集设置动画

时间:2017-07-29 04:09:11

标签: javascript jquery animation chart.js chart.js2

我尝试在折线图中显示两个数据集,但在第一个数据集后几秒钟动画显示第二个数据集。

我使用的是CHART.JS 2.6.0版,我看到了很多使用以前版本(1.xx)的示例,但是所有这些版本都没有在这个新版本中运行,因为API已经改变了。< / p>

我尝试了文档(see here),但对于新手来说实际上非常糟糕,因为ANIMATION事件文档只有一个基本样本。

我想做的基本上是这样的:

DentistID

您可以看到此代码正常运行here,但此示例在版本2.6中不起作用,即使将其调整为新语法也是如此。

那么,你能帮我用Chart.JS 2.6来实现同样的效果吗?

提前致谢!

1 个答案:

答案 0 :(得分:1)

ChartJS v2.6

的解决方案

var done = false;
var data2 = [28, 48, 40, 19, 86, 27, 90];

var ctx = document.getElementById("myChart").getContext("2d");
var myLineChart = new Chart(ctx, {
   type: 'line',
   data: {
      labels: ["January", "February", "March", "April", "May", "June", "July"],
      datasets: [{
         label: "My First dataset",
         backgroundColor: "rgba(220,220,220,0.2)",
         borderColor: "rgba(220,220,220,1)",
         pointBackgroundColor: "rgba(220,220,220,1)",
         pointBorderColor: "#fff",
         pointHoverBackgroundColor: "#fff",
         pointHoverBorderColor: "rgba(220,220,220,1)",
         data: [65, 0, 80, 81, 56, 85, 40]
      }, {
         label: "My Second dataset",
         backgroundColor: "rgba(151,187,205,0.2)",
         borderColor: "rgba(151,187,205,1)",
         pointBackgroundColor: "rgba(151,187,205,1)",
         pointBorderColor: "#fff",
         pointHoverBackgroundColor: "#fff",
         pointHoverBorderColor: "rgba(151,187,205,1)",
         data: [0, 0, 0, 0, 0, 0, 0]
      }]
   },
   options: {
      animation: {
         easing: 'linear',
         onComplete: function(e, i) {
            if (!done) {
               this.data.datasets[1].data = data2;
               /* we need to update chart within setTimeout,
               	as there seems to be an issue when updating the chart 
               	at first animation onComplete function call */
               setTimeout(function() {
                  this.update();
               }.bind(this), 100);
               done = true;
            }
         }
      }
   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="myChart" height="300" width="800"></canvas>