Reputation: 1328
I have created a doughnut chart with
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);
}
}];
Currently, this works and show the value of txt in the middle of doughnut. However, I want the txt to be dynamic. The value is calculated on the click of a button based on some data from the service. I created a class level variable for this. But the trouble is using this.variable is not accessible inside the beforeDraw. how to access this variable ?
Upvotes: 3
Views: 3310
Reputation: 1486
This seems like a hacky solution. But this was the only way I could figure out to fix your issue. Hope it helps.
So, as per ng2-charts
and charts.js
documentation, an options object can be passed to the charts. And whatever values that are passed in this options object can be accessed in the beforeDraw
method through the chart
object. This can be used to achieve the behavior that you require.
Working sample: https://stackblitz.com/edit/ng2-charts-doughnut-centertext-uu3ftp
In this sample, I pass a options object chartOptions
to the chart.
public centerText: String = "Center Text";
public chartOptions: ChartOptions & { annotation: any } = {
centerText: this.centerText
};
In the beforeDraw
method, I access this value like below:
ctx.fillText(chart.options.centerText, centerX, centerY);
To modify this value, you need to set chartOptions
to a new object:
this.chartOptions = {
centerText: "Modified!!"
};
Please note that setting it like this.chartOptions.centerText="Modified!!";
does not work. Also this will redraw the entire chart.
Upvotes: 5