为什么我只使用canvasjs获取最后添加的数据

时间:2015-04-20 12:00:38

标签: javascript canvasjs

 $("#main-content").empty();
 $("#main-content").append(
    "<div class='tab-pane padding-bottom30 active fade in'>" +
    "<div id='chartContainer' style='height: 300px; width: 100%;'>" +
    "</div>" +
    "</div>"
);

for(var i = 0; i < 5; i++) {
    var chart = new CanvasJS.Chart("chartContainer", {
        theme: "theme2", //theme1
        title: {
            text: "Basic Column Chart - CanvasJS"              
        },
        animationEnabled: false, // change to true
        data: [{
            type: "column", // Change type to "bar", "splineArea", "area", "spline", "pie",etc.
            dataPoints: [{ label: i,  y: i * 2  }]
        }]
    });
    chart.render();
}

我正在使用canvasjs来显示我的图表。我想在图表中显示从i = 04的所有数据....但我只获取最后一个附加数据。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

可能是因为chart.render();位于您的for循环中,以及您的图表var本身,所以每次循环结束时都会渲染,你和&#c}} #39; ll只有图表的最后一次迭代(以及dataPoints的最后一个值)。将图表定义移到此循环之外,您只需要dataPoints ...所以看起来如此。请尝试以下

var dataPoints = [];

for (var i = 0; i < 5; i += 1) {

    dataPoints.push({ 'label': i, 'y': (i * 2) })
}

var chart = new CanvasJS.Chart('chartContainer', {
    theme: 'theme2',
    title: {
        text: 'Basic Column Chart - CanvasJS'
    },
    animationEnabled: false,
    data: [
        {
            type: 'column',
            dataPoints: dataPoints
        }
    ]
});

chart.render();