首页 > 解决方案 > 如何获得具有可观察到的居中文本的Chart js?

问题描述

我正在使用 ng2 图表和 chart.js 制作圆环图。

我需要在圆环图中居中文本。我使用了以下方法。

https://stackblitz.com/edit/ng2-charts-doughnut-centertext?file=src%2Fapp%2Fapp.component.html

但是我无法动态更新居中文本的值。

我有一个名为的输入属性

@Input() total;

我想要这个:

  public doughnutChartPlugins: PluginServiceGlobalRegistrationAndOptions[] = [{
    afterDraw(chart) {
      const ctx = chart.ctx;
      const txt = this.total;

      //Get options from the center object in options
      const sidePadding = 60;
      const sidePaddingCalculated = (sidePadding / 100) * (chart.options.circumference / Math.PI)

      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(txt).width;
      const elementWidth = (chart.options.circumference / Math.PI) - sidePaddingCalculated;

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

      // Pick a new font size so it will not be larger than the height of label.
      const fontSizeToUse = Math.min(newFontSize, elementHeight);

      ctx.font = 'Arial';
      ctx.fillStyle = 'white';

      // Draw text in center
      ctx.fillText(this.total, centerX, centerY);
    }
  }];

我怎样才能做到这一点?

目前它显示未定义,因为 afterDraw(chart) 代码在组件初始化之前运行。

或者有没有办法使用 css 来解决它(因为 observable 可以直接在 template.html 中使用)

有人请帮忙。

标签: javascriptangularcharts

解决方案


我面临同样的问题。我通过将“doughnutChartPlugins”定义为公共变量来解决它。您还可以在给定的代码中看到这一点。

public text= 4;
public doughnutChartPlugins: PluginServiceGlobalRegistrationAndOptions[]=[{}];

ngAfterViewInit() {
  let that=this;
  this.doughnutChartPlugins= [{
    beforeDraw(chart) {
      const ctx = chart.ctx;
      //write your code 
      ctx.fillText(that.text, centerX, centerY);
    }
  }]
}

推荐阅读