0

I have working with angular4 and ng2 chart. i need to show the text inside the canvas center of doughnut chart.I am new to angular4 canvas.

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>

i have tried the above code nothing works?the text is not showing anywhere in the canvas. How to add the text center of dough nut chart.?

Library using:

[https://valor-software.com/ng2-charts/][1] 
Doughnut


  [1]: https://valor-software.com/ng2-charts/
Mohamed Sahir
  • 2,482
  • 8
  • 40
  • 71

1 Answers1

3

Build the canvas in component class and insert it dynamically in 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);

          }

Add the below div tag in HTML

<div id="container"></div>
Prithivi Raj
  • 2,658
  • 1
  • 19
  • 34
  • see my question , the doughnut markup is provided by ng2-chart, they are not yet provided support for component class to create the chart. in this situation i need to do the text inside the canvas(center of doughnut chart) – Mohamed Sahir Nov 07 '17 at 07:17