'vue-chartjs - Doughnut chart with text in the middle
I would like to add text inside the chart of Doughnut type.
I'm using this plugin in my vuejs project: https://github.com/apertureless/vue-chartjs
Currently, It's showing for all charts.
I just want to have only Doughnut chart, but it's show all chart.
//*** Doughnut chat ***//
import { Doughnut } from "vue-chartjs";
import Chart from "chart.js";
export default {
extends: Doughnut,
data: () => ({
chartdata: {
labels: ["Cambodia", "Thailand", "Vietnam", "Laos"],
datasets: [
{
label: "Data One",
backgroundColor: ["#a3c7c9", "#889d9e", "#647678", "f87979"],
data: [91, 3, 3, 3]
}
]
},
options: {
legend: {
display: false
},
responsive: true,
maintainAspectRatio: false
}
}),
mounted() {
this.renderChart(this.chartdata, this.options);
this.textCenter(880);
},
methods: {
textCenter(val) {
Chart.pluginService.register({
beforeDraw: function(chart) {
var width = chart.chart.width;
var height = chart.chart.height;
var ctx = chart.chart.ctx;
ctx.restore();
var fontSize = (height / 114).toFixed(2);
ctx.font = fontSize + "em sans-serif";
ctx.textBaseline = "middle";
var text = val;
var textX = Math.round((width - ctx.measureText(text).width) / 2);
var textY = height / 2;
ctx.fillText(text, textX, textY);
ctx.save();
}
});
Chart.plugins.unregister(this.chartdata);
}
}};
//*** end Doughnut chat ***//
Thank you and appreciate.
Solution 1:[1]
If you have a 'tall' legend group (or not), you would like to set the text just in the middle of doughnut, not the canvas itself. So I recommend to change some vars to point to chartArea (the doughnut itself):
const width = chart.chartArea.width;
const height = chart.chartArea.height;
//...
const textY = chart.chartArea.top + height / 2;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Litzer |

