本文介绍了尝试在我的ng2-chart图表上应用渐变:createLinearGradient不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用ng2-charts在画布图表上应用线性渐变我收到此错误:

I'm trying to apply a linear gradient on my canvas chart with ng2-charts I'm getting this error :

DashboardComponent.html:278 ERROR TypeError: this.canvas.createLinearGradient 
is not a function

我的组件:

@ViewChildren('chart') canvas: CanvasRenderingContext2D;
ngAfterViewInit() {
 this.getUserXps(this.id);
 let gradient = this.canvas.createLinearGradient(0, 0, 0, 0);
 console.log(this.canvas);
 gradient.addColorStop(0, 'green');
 gradient.addColorStop(1, 'blue');
 this.lineChartColor[0].backgroundColor = gradient;
}

我的html:

<canvas #chart baseChart height=500 width=1024  [datasets]="lineChartData" 
[labels]="lineChartLabels" [colors]="lineChartColor"
[legend]="lineChartLegend" [chartType]="lineChartType" 
[options]="lineChartOptions" (chartHover)="chartHovered($event)">
</canvas>

推荐答案

您需要将画布声明为ElementRef类型,而不是CanvasRenderingContext2D类型.检查Charlie-Hua在 https://github.com/valor-中提供的解决方案适用于我的软件/ng2-charts/issues/599 .您的代码应类似于:

You need to declare your canvas as an ElementRef type, not CanvasRenderingContext2D. Check the solution Charlie-Hua provides in https://github.com/valor-software/ng2-charts/issues/599, that worked for me.Your code should look something like:

@ViewChild('chart') canvas: ElementRef;

ngOnInit {
    const gradient = this.canvas.nativeElement.getContext('2d').createLinearGradient(0, 0, 0, 200);
    gradient.addColorStop(0, 'blue');
    gradient.addColorStop(1, 'white');
    this.chartColors = [
        {
            backgroundColor: gradient
        }
    ];
}

然后您创建模板:

<canvas #canvasChart baseChart [colors]="chartColors" ......>
</canvas>

这篇关于尝试在我的ng2-chart图表上应用渐变:createLinearGradient不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 17:59