0

我想让我的图表更漂亮一点,并找到渐变效果,但我怎样才能在我的 Angular 项目中正确实现呢?我在网上找到了一些类似的东西,但ERROR TypeError: this.canvas is undefined无论我如何初始化 DOM 元素,我总是得到。有人可以帮我解决这个问题吗?PS 我正在使用 ng2-charts 包。

我的 ViewChild 和我的初始化:

    @ViewChild("canvas") canvas: ElementRef;
  lineChartColors;


  ngAfterContentInit() {
      const domCanvasAccess = this.canvas.nativeElement as HTMLCanvasElement;
      const gradientColor = domCanvasAccess.getContext('2d').createLinearGradient(0, 0, 0, 200);
      gradientColor.addColorStop(0, 'green');
      gradientColor.addColorStop(1, 'white');
      this.lineChartColors = [
        {
          backgroundColor: gradientColor,
          borderColor: "black",
        }
      ];
  }

其余的是StackBiltzhttps ://stackblitz.com/edit/angular-ivy-uop8dm?file=src/app/app.component.ts

4

1 回答 1

0

注意:这就是我在没有ng2-charts 的情况下的做法,

我按照charts.js 文档中的说明创建图表:

 this.chart =  new Chart(
        "canvas",
        {...
        }

然后,在那之后,我添加渐变

const ctx = this.chart.ctx;
const height = this.chart.height;
const gradient = ctx.createLinearGradient(0, 0, 0, height);
gradient.addColorStop(1, "rgba(128, 182, 244, 0.6)");
gradient.addColorStop(0, "rgba(255, 255, 255, 0.6)");
this.chart.data.datasets[0].backgroundColor = gradient;
于 2020-09-16T13:05:01.957 回答