我正在尝试在折线图中显示两个数据集,但在第一个数据集之后几秒钟内对第二个数据集进行动画处理。
我使用的是 CHART.JS 版本 2.6.0,我看到很多使用以前版本 (1.xx( 的示例,但由于 API 已更改,所有这些示例都无法在此新版本中运行。
我尝试了文档(见这里(,但对于新手来说真的很差,因为 ANIMATION 事件文档只有一个基本示例。
我想做的基本上是这样的:
var ctx = document.getElementById("myChart").getContext("2d");
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.2)",
data: [65, 0, 80, 81, 56, 85, 40]
},
{
label: "My Second dataset",
fillColor: "rgba(151,187,205,0.2)",
data: [0, 0, 0, 0, 0, 0, 0]
}
]
};
var data2 = [28, 48, 40, 19, 86, 27, 90];
var done = false;
var myLineChart = new Chart(ctx).Line(data, {
animationEasing: 'linear',
onAnimationComplete: function () {
if (!done) {
myLineChart.datasets[1].points.forEach(function (point, i) {
point.value = data2[i];
});
myLineChart.update();
done = true;
}
}
});
您可以在此处看到此代码的功能,但此示例在版本 2.6 中不起作用,即使它适应新语法也是如此。
那么,你能帮我使用图表.JS 2.6达到同样的效果吗?
提前感谢!
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>