【发布时间】: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