问题
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
My component :
@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;
}
My html :
<canvas #chart baseChart height=500 width=1024 [datasets]="lineChartData"
[labels]="lineChartLabels" [colors]="lineChartColor"
[legend]="lineChartLegend" [chartType]="lineChartType"
[options]="lineChartOptions" (chartHover)="chartHovered($event)">
</canvas>
回答1:
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
}
];
}
And you template:
<canvas #canvasChart baseChart [colors]="chartColors" ......>
</canvas>
来源:https://stackoverflow.com/questions/49067445/trying-to-apply-a-gradient-on-my-ng2-charts-chart-createlineargradient-is-not