javascript - 如何获得具有可观察到的居中文本的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 中使用)
有人请帮忙。
解决方案
我面临同样的问题。我通过将“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);
}
}]
}
推荐阅读
- makefile - 在makefile中使用pdfcrop遍历pdf文件并分配依赖项
- graphql - GraphQL 订阅错误:“\”properties\“参数必须是数组类型。接收类型对象”
- javascript - 如何从异步每个函数返回值?
- vba - 调整PowerPoint演示文稿中所有文本框大小的宏
- java - 在类型 [controller.AppController] 上找不到属性 [姓氏]。为什么?
- node.js - 动态内联键盘按钮(nodejs、telegraf)
- python-3.x - 您如何解析来自 INT8 Calibration of TensorRT 的 bin 文件?
- django - Django 页面导航 - 主页列表不可见
- c# - 复制文件和文件夹检查是否存在
- python - 使用特定的 Miniconda Python 和 NumPy 版本进行 CircleCI 测试