chartjs - 动态更新chartjs图表的值

我使用chartjs创建了一个基本的条形图,它工作正常,现在我想间隔更新值。

我的代码:


var ctx = $("#myChart").get(0).getContext("2d");

var dts = [
 {
 fillColor:"rgba(220,220,220,0.5)",
 strokeColor:"rgba(220,220,220,1)",
 data: [0, 0, 0, 0, 0]
 }
];

var data = {
 labels: ["Core#1","Core#2","Core#3","Core#4","Total"],
 datasets: dts
};

var chart = new Chart(ctx);
chart.Bar(data);

//test code
setInterval( function () { 
 data.datasets[0].data = [random(), random(), random(), random(), random()];
 chart.Bar(data);

},2000);

在测试代码中,我将用datasets[0].data更新值-这是正确的方法?

时间:

根据文档,现在有一个update()方法来绘制图表。

.update()


myBarChart.datasets[0].bars[2].value = 50;
// Would update the first dataset's value of 'March' to be 50
myBarChart.update();
// Calling update now animates the position of March from 90 to 50.

这是一个应该很快就会出现的特性,就像作者所暗示的: https://github.com/nnnick/Chart.js/issues/161#issuecomment-20487775

删除画布dom并再次添加。


function renderChart(label,data){

 $("#canvas-wrapper").html("").html('<canvas id="storeSends"></canvas>');
 var lineChartData = {
 labels : label,
 datasets : [
 {
 fillColor :"rgba(49, 195, 166, 0.2)",
 strokeColor :"rgba(49, 195, 166, 1)",
 pointColor :"rgba(49, 195, 166, 1)",
 pointStrokeColor :"#fff",
 data : data
 }
 ]

 }
 var canvas = document.getElementById("storeSends");
 var ctx = canvas.getContext("2d");

 myLine = new Chart(ctx).Line(lineChartData, {
 responsive: true,
 maintainAspectRatio: false
 });
}

你还可以使用destroy()函数。 像这样


 if( window.myBar!==undefined)
 window.myBar.destroy();
 var ctx = document.getElementById("canvas").getContext("2d");
 window.myBar = new Chart(ctx).Bar(barChartData, {
 responsive : true,
 });

...