角度charts.js圆环图动态设置中心文本

Mob*_* IT 3 ng2-charts angular

我创建了一个圆环图

public doughnutChartPlugins: PluginServiceGlobalRegistrationAndOptions[] = [{
    beforeDraw(chart:any) {
      const ctx = chart.ctx;
      const txt = 'Center Text';

      //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(txt).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 = Math.min(newFontSize, elementHeight);

      ctx.font = fontSizeToUse + 'px Arial';
      ctx.fillStyle = 'blue';

      // Draw text in center
      ctx.fillText(txt, centerX, centerY);
    }
  }];
Run Code Online (Sandbox Code Playgroud)

目前,此功能有效并在甜甜圈中间显示 txt 的值。但是,我希望 txt 是动态的。该值是根据服务中的一些数据单击按钮计算得出的。我为此创建了一个类级别变量。但问题是在 beforeDraw 中无法使用 this.variable 。如何访问这个变量?

小智 5

这似乎是一个很棘手的解决方案。但这是我能找到解决你的问题的唯一方法。希望能帮助到你。

因此,根据ng2-charts文档charts.js,可以将选项对象传递到图表。beforeDraw并且可以通过该对象在方法中访问在此选项对象中传递的任何值chart。这可用于实现您所需的行为。
工作示例:https://stackblitz.com/edit/ng2-charts-doughnut-centertext-uu3ftp
在此示例中,我将选项对象传递chartOptions给图表。

public centerText: String = "Center Text";
public chartOptions: ChartOptions & { annotation: any } = {
  centerText: this.centerText
};
Run Code Online (Sandbox Code Playgroud)

在该beforeDraw方法中,我访问该值如下:

ctx.fillText(chart.options.centerText, centerX, centerY);
Run Code Online (Sandbox Code Playgroud)

要修改该值,需要设置chartOptions为一个新对象:

this.chartOptions = {
  centerText: "Modified!!"
};
Run Code Online (Sandbox Code Playgroud)

请注意,这样设置this.chartOptions.centerText="Modified!!";是行不通的。这也将重新绘制整个图表。