Trying to apply a gradient on my ng2-charts chart : createLinearGradient is not a function

回眸只為那壹抹淺笑 提交于 2020-06-27 04:49:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!