chart.js Failed to create chart: can't acquire context from the given item

I never got into node so I am pretty sure I am doing something massively wrong here since I cannot find any info at all by googling.

I have a django site and I wanted a JS charting library, I chose chart.js.

I installed and like the docs, but after that I am unsure of what to do so I tried to fill in the blanks and follow their guide as much as possible. Here is what my html looks like....

<script src="/public/node_modules/chart.js/dist/Chart.js"></script>

<canvas id="myChart" width="400" height="400"></canvas>

<script>    
    var ctx = document.getElementById("myChart");
    console.log(ctx);

    var options = {}

    var data = {
        labels: ["January", "February", "March", "April", "May", "June", "July"],
        datasets: [
            {
                label: "My First dataset",
                fill: false,
                lineTension: 0.1,
                backgroundColor: "rgba(75,192,192,0.4)",
                borderColor: "rgba(75,192,192,1)",
                borderCapStyle: 'butt',
                borderDash: [],
                borderDashOffset: 0.0,
                borderJoinStyle: 'miter',
                pointBorderColor: "rgba(75,192,192,1)",
                pointBackgroundColor: "#fff",
                pointBorderWidth: 1,
                pointHoverRadius: 5,
                pointHoverBackgroundColor: "rgba(75,192,192,1)",
                pointHoverBorderColor: "rgba(220,220,220,1)",
                pointHoverBorderWidth: 2,
                pointRadius: 1,
                pointHitRadius: 10,
                data: [65, 59, 80, 81, 56, 55, 40],
                spanGaps: false,
            }
        ]
    };

    var myChart = new Chart({
        type: 'line',
        data: data,
        options: options
    })
</script>

I am just trying to get an example working. I put the node_modules directory that was downloaded via npm somewhere where my server would serve them up....and verified they are being served, but then I get this error when I try to build a chart. I took all the chart codes from their docs so I am pretty sure that part is right, but I can't see why I am getting this error.


Another reason to get the same error, is if the element referred by the id is not a <canvas>. I had a <div> element in my HTML source, and of course it did not work.


You are not passing the 2d context of the canvas (ctx) when calling the constructor. From the documentation:

To create a chart, we need to instantiate the Chart class. To do this, we need to pass in the node, jQuery instance, or 2d context of the canvas of where we want to draw the chart.

<canvas id="myChart" width="400" height="400"></canvas>

Make sure to declare the canvas tag in html before the script that creates the Chart.js object. Otherwise the script executes and tries to find a reference to a canvas that dosen't exists. In the script, any of the following formats may be used to get reference to the canvas, which is then passed to the Chart.js constructor.

var ctx = document.getElementById('myChart'); // node
var ctx = document.getElementById('myChart').getContext('2d'); // 2d context
var ctx = $('#myChart'); // jQuery instance
var ctx = 'myChart'; // element id

var myChart = new Chart(ctx, {
  type: 'line',
  data: {/* Data here */},
  options: {/* Options here */}
}

I am a bit late to the party but if other developers reach this post, make sure you don't reference document or window. The angular team doesn't encourage accessing the dom variable directly. Use ElementRef instead

import { Component, OnInit, ElementRef } from '@angular/core';
@Component({
  selector: 'my-compo',
  templateUrl: 'mycompo.html',
})
export class MyCompo implements OnInit {
   myChart:any;
   constructor(private elementRef: ElementRef) {
   }

  ngOnInit(){
   this.chartit();
  }

  chartit(){
     let htmlRef = this.elementRef.nativeElement.querySelector(`#yourCavasId`);
     this.myChart = new Chart(htmlRef, {
        //your data here
     });
  }

}

HTML as suggested by @mavroprovato

<canvas id="yourCavasId" ></canvas>

Also, the java script must be after the declaration of the canvas.


Had this error cause I was trying to set the chart on constructor instead of ngAfterContentInit

I personally have no problem with giving the canvas id as string for context

this.chart = new Chart('myChartId', {...})