ARCAON
ARCAON

Reputation: 59

Chart.js error: Bar is not a function

        <canvas id="chart" width="600" height="600"></canvas>
        <script>
           var barData = {
           labels : [{% for item in labels %}
                          "{{item}}",
                      {% endfor %}],
           datasets : [
              {
                    fillColor: "rgba(151,187,205,0.2)",
                    strokeColor: "rgba(151,187,205,1)",
                    pointColor: "rgba(151,187,205,1)",
                 data : [{% for item in values %}
                              {{item}},
                            {% endfor %}]
              }
              ]
           };

           var mychart = document.getElementById("chart").getContext("2d");

           steps = 10;
           max = 10;    
           // draw bar chart
           new Chart(mychart).Bar(barData, {
                scaleOverride: true,
                scaleSteps: steps,
                scaleStepWidth: Math.ceil(max / steps),
                scaleStartValue: 0,
                scaleShowVerticalLines: true,
                scaleShowGridLines : true,
                barShowStroke : true,
                scaleShowLabels: true
           });
        </script>

It makes an error:(index):61

Uncaught TypeError: (intermediate value).Bar is not a function at (index):61

I already try chart.js, chart.min.js and Chart.bundle.js, in vain!

Upvotes: 0

Views: 6587

Answers (1)

ɢʀᴜɴᴛ
ɢʀᴜɴᴛ

Reputation: 32879

This is because you are using old syntax (used in ChartJS 1.x) for creating your chart, and you might be using the latest version (2.7.0) of ChartJS library.

In latest version of ChartJS, you should create your chart as follows :

var mychart = document.getElementById("chart").getContext("2d");

new Chart(mychart, {
   type: 'bar',
   data: {
      labels: [{% for item in labels %}
                    "{{item}}",
               {% endfor %}],
      datasets: [{
         data: [{% for item in values %}
                    {{item}}, 
                {% endfor %}],
         backgroundColor: 'rgba(151,187,205,0.2)',
         borderColor: 'rgba(151,187,205,1)',
         pointBackgroundColor: 'rgba(151,187,205,1)'
      }]
   },
   options: {
      scales: {
         yAxes: [{
            ticks: {
               beginAtZero: true,
               stepSize: 10
            }
         }]
      }
   }
});

Refer to the official documentation to learn more.

Upvotes: 3

Related Questions