>我正在使用 angular4 和 ng2 图表。 我需要在甜甜圈图的画布中心显示文本。我是 angular4 画布的新手。
Here is my app.component:
export class AppComponent {
@ViewChild("layout") layout: ElementRef;
ngAfterViewInit() {
let canvas = this.layout.nativeElement;
let context: CanvasRenderingContext2D = this.layout.nativeElement.getContext("2d");
var x = canvas.width / 2;
var y = canvas.height / 2;
context.font = '90pt Calibri';
context.textAlign = 'center';
context.fillStyle = 'blue';
context.fillText('Hello Worldetrereygerhg!', x, y);
}
here is my app.component.html
<div style="display: block; background-color: #e2d8d8;">
<canvas baseChart
[data]="doughnutChartData"
[colors]="doughnutChartColors"
[labels]="doughnutChartLabels"
[chartType]="doughnutChartType"
(chartHover)="chartHovered1($event)"
(chartClick)="chartClicked1($event)" #layout ></canvas>
</div>
我已经尝试了上面的代码没有任何效果?文本没有显示在画布中的任何位置。 如何添加面团图的文本中心。?
Library using:
[https://valor-software.com/ng2-charts/][1]
Doughnut
[1]: https://valor-software.com/ng2-charts/
在组件类中构建画布并将其动态插入到 HTML 中
export class AppComponent {
canvas: HTMLCanvasElement;
ctx: CanvasRenderingContext2D ;
container : any;
cw : any;
ch : any;
ngAfterViewInit() {
this.container = document.getElementById('container');
this.cw = container.clientWidth;
this.ch = container.clientHeight;
this.canvas = document.createElement('canvas');
this.ctx = this.canvas.getContext('2d');
this.canvas.width = this.cw;
this.canvas.height = this.ch;
container.appendChild(this.canvas);
}
在 HTML 中添加以下div 标记
<div id="container"></div>