如何在画布中动态设置数据点?

时间:2015-08-07 10:53:14

标签: javascript canvas

我需要一些帮助在javascript画布中动态设置数据点。

这是我现在的代码:

var dps = [{x: 1, y: 100}, {x: 2, y: 50}, {x: 3, y: 250}, {x: 4, y: 120}, {x: 5, y: 400}];  
window.onload = function () {
        var chart = new CanvasJS.Chart("chartContainer",
        {               
         data: [
                {        
                type: "line",
                lineThickness:3,
                axisYType:"primary", // for align the y to right 
                showInLegend: true,           
                name: "India", 
                dataPoints: dps
            }
            ],
        });

chart.render();
}

这很好用,但我想让数据设置部分动态化,如下所示:

    data: [
for( var i = 0 ; i < array.length ; i++ ){
                {        
                type: "line",
                lineThickness:3,
                axisYType:"primary", // for align the y to right 
                showInLegend: true,           
                name: array[i]['title'], 
                dataPoints: array[i]['data']
            }
}
            ],

我该怎么做?

1 个答案:

答案 0 :(得分:2)

这是执行此操作的正确方法。

var dps = [{x: 1, y: 100}, {x: 2, y: 50}, {x: 3, y: 250}, {x: 4, y: 120}, {x: 5, y: 400}];  
window.onload = function () {
var data = [];
for( var i = 0 ; i < array.length ; i++ ){
              data.push(  {        
                type: "line",
                lineThickness:3,
                axisYType:"primary", // for align the y to right 
                showInLegend: true,           
                name: array[i]['title'], 
                dataPoints: array[i]['data']
            });
}

        var chart = new CanvasJS.Chart("chartContainer",
        {               
         data: data,
        });

chart.render();
}