【问题标题】:angular charts.js doughnut chart setting center text dynamically角charts.js圆环图动态设置中心文本
【发布时间】:2020-10-03 08:45:03
【问题描述】:

我用

创建了一个圆环图
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);
    }
  }];

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

【问题讨论】:

    标签: angular ng2-charts


    【解决方案1】:

    这似乎是一个 hacky 解决方案。但这是我能解决您的问题的唯一方法。希望对您有所帮助。

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

    public centerText: String = "Center Text";
    public chartOptions: ChartOptions & { annotation: any } = {
      centerText: this.centerText
    };
    

    beforeDraw 方法中,我访问这个值如下:

    ctx.fillText(chart.options.centerText, centerX, centerY);
    

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

    this.chartOptions = {
      centerText: "Modified!!"
    };
    

    请注意,将其设置为this.chartOptions.centerText="Modified!!"; 不起作用。这也将重绘整个图表。

    【讨论】:

    • 上面的问题是错误 Object literal may only specify known properties, and 'centerText' does not exist in type 'ChartOptions & { annotation: any; }'。如果您修改 ng2-chats.d.ts 中的任何内容(例如添加分号),它就会消失,但这还不足以编译代码
    • 在 stackblitz 中,未显示此错误。但是当我使用 angular cli 创建一个示例时,就出现了这个错误。我也会尝试修复它。我试图想出一个不重绘整个图表的解决方案。它几乎起作用了,但还有另一个问题。每第二次点击,中心文本的字体就会变小。
    • 好吧,我不需要修改文本。我只需要动态传递它
    • 请检查此示例。它不使用选项对象。它使用动画事件onComplete 来绘制中心文本:stackblitz.com/edit/ng2-charts-doughnut-centertext-1kc2pg
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-21
    • 1970-01-01
    • 2015-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多