Angular 2 ng2-charts donut 文字在中间?

标签 angular chart.js ng2-charts

我在 Angular 2 中使用来自 ng2-charts ( http://valor-software.com/ng2-charts/ ) 的圆环图。 我一直在寻找将文本放在中间但没有成功的选项。 我已经在 chart.js(依赖项)中搜索了 ng-chart 选项。 你知道在 Angular 2 typescript 中实现这一目标的另一种方法吗?还是我缺少什么?

最佳答案

您可以将 LABEL 及其值都放在 Doughnut 的中心。

当您悬停它时,悬停值将在图表中心更新。

import { Component, OnInit } from '@angular/core';
import { ChartType } from 'chart.js';
import { SingleDataSet, Label, PluginServiceGlobalRegistrationAndOptions } from 'ng2-charts';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  // Doughnut
  public doughnutChartLabels = ['Download Sales', 'In-Store Sales'];
  public doughnutChartData: SingleDataSet = [
    [350, 450]
  ];
  public doughnutChartType: ChartType = 'doughnut';
  public doughnutChartPlugins: PluginServiceGlobalRegistrationAndOptions[] = [{
    afterDraw(chart) {
      const ctx = chart.ctx;
      var txt1 = '';
      var txt2 = '';    

      try{
        var check = chart.active ? chart.tooltip._active[0]._datasetIndex : "None";
        if(check !== "None"){
        txt1 = chart.tooltip._data.labels[chart.tooltip._active[0]._index];
        txt2 = chart.tooltip._data.datasets[0].data[chart.tooltip._active[0]._index];        
      }else{
        txt1 = chart.tooltip._data.labels[0];
        txt2 = chart.tooltip._data.datasets[0].data[0];
      }
      }
      catch(err){
        txt1 = chart.tooltip._data.labels[0] 
        txt2 = chart.tooltip._data.datasets[0].data[0];
      }
      //Get options from the center object in options
      const sidePadding = 60;
      const sidePaddingCalculated = (sidePadding / 100) * (chart.innerRadius * 2)

      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      const centerX = ((chart.chartArea.left + chart.chartArea.right) / 2);
      const centerY = ((chart.chartArea.top + chart.chartArea.bottom) / 2);

      //Get the width of the string and also the width of the element minus 10 to give it 5px side padding

      const stringWidth = ctx.measureText(txt1).width;
      const elementWidth = (chart.innerRadius * 2) - sidePaddingCalculated;

      // Find out how much the font can grow in width.
      const widthRatio = elementWidth / stringWidth;
      const newFontSize = Math.floor(30 * widthRatio);
      const elementHeight = (chart.innerRadius * 2);

      // Pick a new font size so it will not be larger than the height of label.
      const fontSizeToUse = 30;
      ctx.font = fontSizeToUse + 'px Arial';
      ctx.fillStyle = 'black';

      // Draw text in center
      ctx.fillText(txt2, centerX, centerY - 10);
      var fontSizeToUse1 = 15;
      ctx.font = fontSizeToUse1 + 'px Arial';
      ctx.fillText(txt1, centerX, centerY + 10);
    }
  }];

  constructor() { }

  ngOnInit() {
  }

  // events
  public chartClicked({ event, active }: { event: MouseEvent, active: {}[] }): void {
    //console.log(event, active);
  }

  public chartHovered({ event, active }: { event: MouseEvent, active: {}[] }): void {
    //console.log(event, active);
  }
}

HTML

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

enter image description here

快乐编码:)

关于Angular 2 ng2-charts donut 文字在中间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42662539/

相关文章:

javascript - Chart.js 结合了具有不同数据点的折线图和条形图

angular - 图表单击事件 - 单击圆环图的标签,不返回标签 ng2-charts

angularjs - Angular 2 成熟度 : going in prod with usable components

Angular2 无法解析 RouterOutlet : (RouterOutletMap, ViewContainerRef,?,名称的所有参数)

jquery - 是否可以在 Chart.js 的雷达图中设置扇区的背景颜色?

chart.js - 图表js仅在迷你图上显示2个数据点

javascript - Promise.all 不会等待所有 promise 得到解决

Angular 5,IE11 中的 URLSearchParams

angular - ng2-图表 : How to show percentage values inside the chart?

jquery - ng2-charts 实时数据动画