2017-03-08 61 views

回答

3

您可以執行以下操作將文字置於圓環圖的中央。它的工作對我來說

HTML:

<div style="display: block"> 
    <canvas #mycanvas baseChart 
       [data]="doughnutChartData" 
       [labels]="doughnutChartLabels" 
       [chartType]="doughnutChartType" 
       (chartHover)="chartHovered($event)" 
       (chartClick)="chartClicked($event)"></canvas> 
</div> 

打字稿

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(); 
     } 
} 
} 
+0

真棒!這適用於我,我只需將文本放置在圖表的中間,所以'textY'變量應該是:'textY = height/2'。另外,似乎每當鼠標懸停在圖表上時,函數'doit'被調用,所以文本消失並再次出現。所以,你應該做下一個,以解決它.. https://stackoverflow.com/a/43286397/2621320 –