Angular 2 ng2-charts doughnut text in the middle?

前端 未结 2 1376
隐瞒了意图╮
隐瞒了意图╮ 2021-02-14 01:19

I am using Doughnut chart from ng2-charts (http://valor-software.com/ng2-charts/) in angular 2. I have been searching for an option to put a text in the middle without success.

2条回答
  •  死守一世寂寞
    2021-02-14 02:09

    You can do the following to place text in the center of doughnut chart. It worked for me

    HTML:

     

    Typescript

    import {Component, NgModule, ElementRef, Inject, ViewChild} from '@angular/core'
    import {BrowserModule} from '@angular/platform-browser'
    import {ChartsModule, Color} from 'ng2-charts';
    
    export class App{
       @ViewChild('mycanvas')
      canvas:ElementRef; 
    
     ngOnInit(){
        var ctx = this.canvas.nativeElement.getContext("2d");
    
        let me = this;
        this.options = {
    
          circumference: Math.PI,
          rotation :  Math.PI,
          animation:{ onComplete: function() {
             me.doit(ctx);
           }}
        }
    
          }
    
         doit(ctx) {
             //   Chart.types.Doughnut.prototype.draw.apply(this, arguments);
    
                var width = this.canvas.nativeElement.clientWidth,
                    height = this.canvas.nativeElement.clientHeight;
    
                var fontSize = (height / 250).toFixed(2);
                ctx.font = fontSize + "em Verdana";
                ctx.textBaseline = "middle";
                ctx.fillStyle = "blue";
    
                var text = "Pass Rate 82%",
                    textX = Math.round((width - ctx.measureText(text).width) / 2),
                    textY = height -10;
    
                ctx.fillText(text, textX, textY);
                ctx.restore();
            }
    }
    }
    

提交回复
热议问题