首页 > 解决方案 > 图表 js 图形未显示在画布上

问题描述

这是我从 chart.js 网站https://www.chartjs.org/docs/master/getting-started/usage.html的教程中获得的代码 我也关注了这个视频https://www.youtube.com /watch?v=ZCYiUCcTo20完全正确,所以不确定我哪里出错了。研究了很多,但找不到我的具体问题。提前感谢您的帮助。

import { Component, OnInit } from '@angular/core';
import { Chart } from '../../../node_modules/chart.js'

@Component({
  selector: 'app-recent-graph',
  templateUrl: './recent-graph.component.html',
  styleUrls: ['./recent-graph.component.css']
})
export class RecentGraphComponent implements OnInit {

  constructor() { }

  ngOnInit() {
    var myChart = new Chart("myChart", {
      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
              }
          }
      }
  });
  }

}
'''

HTML:

 '''
<div id="divChart">
    <canvas id="myChart"></canvas>
</div>
'''

标签: angularjschart.js

解决方案


您的图表导入是错误的,如果您使用这样的括号,则必须导入所有要使用的组件并注册它们,或者您可以忽略 treeshaking 并让图表处理它,如果您像这样导入它import Chart from 'chart.js/auto'

有关 treeshaking 导入和注册,请参阅文档


推荐阅读