javascript - 如何以 Angular 获取具有可观察居中文本的 Chart js?

标签 javascript angular charts

我正在使用 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 来解决它(因为可观察对象在 template.html 中直接可用)

有人请帮助。

最佳答案

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

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

关于javascript - 如何以 Angular 获取具有可观察居中文本的 Chart js?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61622342/

相关文章:

javascript - 具有特定顺序的 C3JS 条形图

apache - 如何使用 Apache POI 从 Excel 电子表格获取图表信息?

javascript - Angularjs Kendo 主从网格应用主从的默认 ID 以添加新的详细记录

javascript - 右侧的 float 组件指示页面中的部分

javaScript 检查字符串中至少一个字母数字字符

google-maps - Ionic 2 Segments 不适用于谷歌地图

angular - angular2 karma 测试的新手 - 添加 app.module 到 TestBed.configureTestingModule

javascript - 通过json对数据进行计算

javascript - 如何防止 Angular2 核心在页面加载时发出数十个 HTTP 请求?

javascript - Chart.js 条形图基于Label加载数据