如何使用primeng/chart.js将文本放置在圆环图中?

xqk2d5yq  于 2022-11-06  发布在  Chart.js
关注(0)|答案(2)|浏览(145)

我正在制作一个原始图表,并开发一个圆环图沿着Angular 图。现在我需要按照设计显示圆环图内部的文本。如下图所示
image link
我的HTML:

<p-chart
            type="doughnut"
            [data]="inspectionStorage"
            [options]="doughnutOptions"
          ></p-chart>

我的组件端代码:

this.inspectionStorage = {
              labels: ['Completed', 'Due', 'Pending', 'Deficient', 'Report'],
              datasets: [
                {
                  data: [],
                  backgroundColor: [
                    'green',
                    '#51087E',
                    '#ffd740',
                    'red',
                    '#5500FF',
                  ],
                },
              ],
            };

            this.doughnutOptions = {
              responsive: true,
              plugins: {
                legend: {
                  position: 'right',
                  labels: {
                    boxWidth: 17,
                    boxHeight: 15,
                    color: '#000000',
                  },
                },
              },
            };

但是我不能得到我所期望的结果的确切方式。那么,在这个问题上有没有人给我建议?

u7up0aaq

u7up0aaq1#

有一个特定的插件(但我从来没有测试过)https://github.com/alexkuc/chartjs-plugin-doughnutlabel-rebourne
或者,您可以开发自己的插件来实现这一点(代码片段只是解决您的用例的起点)。
第一个

vbopmzt1

vbopmzt12#

app.component.ts

import { Component, OnInit } from '@angular/core';
import { Chart } from 'chart.js';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  chart: any;

  ngOnInit() {
    this.chart = new Chart('canvas', {
      type: 'doughnut',
      data: {
        labels: ['Data1', 'Data2'],
        datasets: [
          {
            data: [55, 45],
            backgroundColor: ['rgba(255, 0, 0, 1)', 'rgba(255, 0, 0, 0.1)'],
            fill: false,
          },
        ],
      },
      options: {
        legend: {
          display: false,
        },
        tooltips: {
          enabled: false,
        },
      },
      plugins: [
        {
          id: 'text',
          beforeDraw: function (chart, a, b) {
            var width = chart.width,
              height = chart.height,
              ctx = chart.ctx;

            ctx.restore();
            var fontSize = (height / 114).toFixed(2);
            ctx.font = fontSize + 'em sans-serif';
            ctx.textBaseline = 'middle';

            var text = '75%',
              textX = Math.round((width - ctx.measureText(text).width) / 2),
              textY = height / 2;

            ctx.fillText(text, textX, textY);
            ctx.save();
          },
        },
      ],
    });
  }
}

the working example is here

相关问题