Skip to content

Failed to create chart: can't acquire context from the given item #2

@nukec

Description

@nukec

For anyone who has an issue with angular 5 and canvas, you have to do it like this:

Html:

<div *ngIf="chart">
    <canvas #myCanvas>{{ chart }}</canvas>
</div>

Use viewchild for angular, don't use js getelementbyid:

@ViewChild('myCanvas') myCanvas: ElementRef;
    public context: CanvasRenderingContext2D;

Method inside component:

gettest(): void{
    this.weatherApi
    .dailyForecast()
    .subscribe(res => {
      
        let temp_max = res['list'].map(res => res.main.temp_max);
        let temp_min = res['list'].map(res => res.main.temp_min);
        let alldates = res['list'].map(res => res.dt)

        let weatherDates = []
        alldates.forEach((res) => {
            let jsdate = new Date(res * 1000)
            weatherDates.push(jsdate.toLocaleTimeString('en', { year: 'numeric', month: 'short', day: 'numeric' }))
        })

        this.context = (<HTMLCanvasElement>this.myCanvas.nativeElement).getContext('2d');
        this.chart = new Chart(this.context, {
            type: 'line',
            data: {
              labels: weatherDates,
              datasets: [
                { 
                  data: temp_max,
                  borderColor: "#3cba9f",
                  fill: false
                },
                { 
                  data: temp_min,
                  borderColor: "#ffcc00",
                  fill: false
                },
              ]
            },
            options: {
              legend: {
                display: false
              },
              scales: {
                xAxes: [{
                  display: true
                }],
                yAxes: [{
                  display: true
                }],
              }
            }
          });

    })

as you can see you have to properly access context. also initialization of this should be in:

ngAfterViewInit() {
    this.gettest();
  }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions