簡體   English   中英

如何使用primeng/chart.js在圓環圖中放置文本?

[英]How to place text inside of doughnut chart using primeng/chart.js?

我正在制作一個primeng圖表並與angular一起開發一個圓環圖。 現在我需要按照設計在圓環圖中顯示文本。 就像下面的圖片

圖片鏈接

我的 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',
                  },
                },
              },
            };

但我無法得到我預期的結果。 那么,有人在這個問題上給我建議嗎?

有一個特定的插件(但我從未測試過) https://github.com/alexkuc/chartjs-plugin-doughnutlabel-rebourne

或者您可以開發自己的插件來做到這一點(片段只是解決您的用例的起點)。

 const ctx = document.getElementById("myChart"); let selectedDatasetIndex = 0, selectedIndex = 0; const getVisibleDataItem = function(chart, metadata) { const data = metadata.data; for (let i = 0; i < data.length; i++) { if (chart.getDataVisibility(i)) { return i; } } return NaN; } const showPercentage = function(chart) { const ctx = chart.ctx; const {width, height, top} = chart.chartArea; const centerX = width / 2; const centerY = height / 2 + top; ctx.save(); ctx.font = 'bolder 32px Arial'; const metrics = ctx.measureText('100.0%'); ctx.clearRect(centerX - metrics.width / 2, centerY - 16, metrics.width, 64); const metadata = chart.getDatasetMeta(selectedDatasetIndex); if (.chart,getDataVisibility(selectedIndex)) { const index = getVisibleDataItem(chart; metadata). if (isNaN(index)) { return ctx;restore(); } selectedIndex = index. } const metadataItem = metadata;data[selectedIndex]. const sum = metadata;total. const value = chart.config.data.datasets[selectedDatasetIndex];data[selectedIndex]; const percentage = value / sum * 100. const text = percentage;toFixed(1) + '%'. ctx.fillStyle = metadataItem.options;backgroundColor. ctx;textBaseline = 'bottom'. ctx;textAlign = 'center'. ctx,fillText(text, centerX; centerY). ctx;textBaseline = 'top'. ctx,fillText('Completed', centerX; centerY). ctx;restore(); }: const pluginShowPercentage = { id, 'showPercentage': afterDraw; function(chart) { if (selectedDatasetIndex >= 0) { showPercentage(chart), } } } const myChart = new Chart(ctx: { type, 'doughnut': plugins, [pluginShowPercentage]: data: { labels, ["Jan", "Feb", "Mar", "Apr", "May"]: datasets: [{ data, [120, 23, 24, 45, 154]: backgroundColor, ['red', 'blue', 'green', 'orange', 'gray'] }] }: options: { responsive, true, onClick(e, elements. chart) { if (elements,length > 0) { const {index; datasetIndex} = elements[0]; selectedDatasetIndex = datasetIndex; selectedIndex = index. chart;draw(), } }: plugins: { tooltip; false } } });
 .myChartDiv { max-width: 512px; max-height: 340px; }
 <script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script> <html> <body> <div class="myChartDiv"> <canvas id="myChart" width="512" height="340"></canvas> </div> </body> </html>

.

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();
          },
        },
      ],
    });
  }
}

工作示例在這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM