[Chartjs]-Cannot initialize a pie chart with Chart.js

5👍

Two issues with your code.

First, you are assigning properties to data after it’s passed to Chart(), so the pie chart will appear empty since you are not passing any data.

Second, the .getContext('2d') does not return an array but a singular rendering context (or null). So ctx[0] is undefined.

Modify your code as follows and it should work.

var ctx = document.getElementById("myChart").getContext("2d");

var data = [{
    value: 300,
    color: "#F7464A",
    highlight: "#FF5A5E",
    label: "Red"
}, {
    value: 50,
    color: "#46BFBD",
    highlight: "#5AD3D1",
    label: "Green"
}, {
    value: 100,
    color: "#FDB45C",
    highlight: "#FFC870",
    label: "Yellow"
}];

var myNewChart = new Chart(ctx).Pie(data);

0👍

the problem is here

var myNewChart = new Chart(ctx[0]).Pie(data);

ctx[0] is undefined.

Use this:

var myNewChart = new Chart(ctx).Pie(data);

Leave a comment