Chartjs-Chartjs creating data array dynamically

1👍

You just need to generate the data structure in the way Chart.js expects for a pie chart and if you don’t know the maximum number of element generate the colors (if you know the maximum number of elements, you could just pick it from a color array). For instance

var dynamicData = [
    { label: "One", value: 23 },
    { label: "Two", value: 33 },
    { label: "Three", value: 43 },
    { label: "Four", value: 53 },
]

dynamicData.forEach(function (e, i) {
    e.color = "hsl(" + (i / dynamicData.length * 360) + ", 50%, 50%)";
    e.highlight = "hsl(" + (i / dynamicData.length * 360) + ", 50%, 70%)";
    // + any other code you need to make your element into a chart.js pie element
})

var ctx = document.getElementById("myChart").getContext("2d");
var myPieChart = new Chart(ctx).Pie(dynamicData);

Fiddle – http://jsfiddle.net/k4ztyqzc/

Leave a comment