[Chartjs]-Chart.js Failed to create chart: can't acquire context from the given item

86👍

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 doesn’t exist. In the script, any of the following formats may be used to get a 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 */}
});

147👍

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.

22👍

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>

9👍

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

5👍

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', {...})

4👍

I’m using Chart.JS with Angular 9.

This usually happens if there is an ID mismatch with the instantiation of the chart.
Make sure you have an ID attribute in canvas element like this –

<canvas id="myCanvasId">{{ myChart }}</canvas>

and you have this correctly while instantiating the chart –

this.myChart = new Chart('myCanvasId', {
....
}

On another screen, I faced the same issue due to the presence of *ngIf on the parent element of <canvas>.

To overcome this, you can either remove the *ngIf from the parent or initialize the chart variable at the beginning with an empty array – myChart: [].

3👍

you can use

add this in your template
<canvas #myCanvas width="500" height="300"></canvas>

add this to your component

@ViewChild('myCanvas') canvasRef: ElementRef;
  constructor()

when ready to draw call this

 this.ctx = this.canvasRef.nativeElement.getContext('2d');
         this.chart = new Chart(this.ctx, {....})

2👍

Also faced this issue, mine was solved by putting the chart creation in a DOMContentLoaded addEventListener. Of course the CDN and canvas prerequisites have to be met before doing this

document.addEventListener("DOMContentLoaded", function () {

    const ctx = document.getElementById("myChart")

    const myChart = new Chart(ctx, {
        type: "bar",
        data: {
            labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
            datasets: [
                {
                    label: "# of Votes",
                    data: [12, 19, 3, 5, 2, 3],
                    backgroundColor: [
                        "rgba(255, 99, 132, 0.2)",
                        "rgba(54, 162, 235, 0.2)",
                        "rgba(255, 206, 86, 0.2)",
                        "rgba(75, 192, 192, 0.2)",
                        "rgba(153, 102, 255, 0.2)",
                        "rgba(255, 159, 64, 0.2)",
                    ],
                    borderColor: [
                        "rgba(255, 99, 132, 1)",
                        "rgba(54, 162, 235, 1)",
                        "rgba(255, 206, 86, 1)",
                        "rgba(75, 192, 192, 1)",
                        "rgba(153, 102, 255, 1)",
                        "rgba(255, 159, 64, 1)",
                    ],
                    borderWidth: 1,
                },
            ],
        },
        options: {
            scales: {
                y: {
                    beginAtZero: true,
                },
            },
        },
    });
});

1👍

In my case, I was using ngIf on canvas and then I moved it to its parent div. In both cases I was getting this error: chart.js Failed to create chart: can’t acquire context from the given item.

Even after applying all the above methods, I wasn’t able to solve it. So I changed ngIf to ngStyle with display: (condition)? none: block. And it worked for me.

1👍

In my case, I was using ngIf on canvas and then I moved it to its parent div. In both cases I was getting this error: chart.js Failed to create chart: can't acquire context from the given item.

Even after applying all the above methods, I wasn’t able to solve it. So I changed ngIf to ngStyle with display: (condition)? none: block. And it worked for me.

0👍

Just a little tip. If you fixed the issue by adding a context, but the chart still doesn’t show up, then place the <canvas> element in a <div> element, otherwise it won’t display.

Reference: Charts.js sets canvas width/height to 0 and displays nothing

Leave a comment