【问题标题】:Chart.js Error: Failed to create chart: can't acquire context from the given itemChart.js 错误:无法创建图表:无法从给定项目获取上下文
【发布时间】:2020-11-12 04:05:09
【问题描述】:

我正在尝试使用 chart.js 在我的 Angular 应用程序中实现一个简单的图表。但不幸的是,我收到以下错误:

创建图表失败:无法从给定项目获取上下文

我已经在这里找到了几个类似的问题,但不知何故,没有一个答案真正有帮助。有谁知道如何解决这个问题?

task-activity.component.html

        <nb-tab tabIcon="bar-chart-2-outline" tabTitle="Insights">
          <div id="divChart">
            <canvas id="myChart" width="400px" height="400px"></canvas>
          </div>
        </nb-tab>

task-activity.component.ts

import { Component, Input, ViewChild, OnInit, AfterViewInit, TemplateRef } from '@angular/core';
import { Chart }  from 'chart.js';

@Component({
  selector: 'ngx-task-activity',
  templateUrl: './task-activity.component.html',
  styleUrls: ['./task-activity.component.scss'],
})
export class TaskActivityComponent implements OnInit, AfterViewInit {

  chart= [];

  constructor(private dialogService: NbDialogService,
    public organizationService: OrganizationService) {
      this.userId = organizationService.getUserId();
      console.info('this.userId:', this.userId);

      setTimeout(() => {
        this.user = organizationService.getUser();
      }, 2000);

  }

  ngOnInit() {
    this.initData();

    this.chart.push(new Chart('myChart', {
      // The type of chart we want to create
      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: {
              yAxes: [{
                  ticks: {
                      beginAtZero: true
                  }
              }]
          }
      }
  }));

  }

【问题讨论】:

    标签: javascript node.js angular charts


    【解决方案1】:

    这是关于如何使用 ng2-charts 包动态更新 angular-chatr.js 图表的答案。确保将 node_modules/dist/Chart.min.js 包含到您的 Web 清单中,或作为 index.html 中的链接

    请访问此 https://stackoverflow.com/a/64793266/12683543

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-07
      • 1970-01-01
      • 1970-01-01
      • 2020-07-10
      • 2019-10-21
      • 2020-09-18
      • 2015-05-20
      • 2021-06-14
      相关资源
      最近更新 更多