我正在使用 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/