Search code examples
javascriptchart.jspie-chart

Cannot initialize a pie chart with Chart.js


I am copying the example from Chart.js and I am stuck as to what the error I am making is.

Here is my code (taken from the examples):

<canvas id="myChart" width="400" height="400"></canvas>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src=" https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js" charset="utf-8"></script>
<script type="text/javascript">
    // Get the context of the canvas element we want to select
    var ctx = document.getElementById("myChart").getContext("2d");
    var myNewChart = new Chart(ctx[0]).Pie(data);
    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"
    }]
</script>

This code gives me an error:

Uncaught TypeError: Cannot read property 'canvas' of undefined

Now if I change the myNewChart var to:

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

I get no error and no chart.

What am I missing? I feel it's something obvious...

Thanks


Solution

  • 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);