0

我正在使用 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/
4

1 回答 1

3

在组件类中构建画布并在 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>
于 2017-11-07T07:12:14.017 回答