Search code examples
javascriptcanvascanvasjs

chart canvas js set dynamic array


I receive json, and try set dynamic array to dataPoints of chart canvasJS, maybe somebody can help please,

this the code:

for(var i=0;i<cars.length; i++) {
    cars[i] =100 * (cars[i]/cars.length);
}

for(var j=0;j<cars.length; j++){
    dps.push({
        y: cars[j], label: models[j]
    });
}

And this code how I build canvasJS chart:

var chart = new CanvasJS.Chart("chartContainer", {
    animationEnabled: true,
    title: {
        text: "Sum of Cars"
    },
    data: [{
        type: "pie",
        startAngle: 240,
        yValueFormatString: "##0.00\"%\"",
        indexLabel: "{label} {y}",
        dataPoints: dps
    }]
});    

chart.render();

Solution

  • Updating dps won't have any effect on the CanvasJS Chart Options. You will either have to update the chart options yourself and re-render the chart.

    for(var i = 0; i < data.length; i++) {
        chart.options.data[0].dataPoints.push(data[i]);
    }
    

    The second approach would be updating the dataPoints using set() method.

    chart.data[0].set("dataPoints", data);
    

    Note the chart has to be rendered before you can use any set() method.

    Have a look at these examples:

    1. Updating dataPoints using chart options.
    2. Updating dataPoints using set method.