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

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>

Any of the following formats may be used:

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>