Reputation:
I want to write text center of donut chart. I wrote this code below
<script>
$(document).ready(function () {
var data = {
labels: [
""
],
datasets: [
{
data: [165],
backgroundColor: [
"#FF6384"
],
hoverBackgroundColor: [
"#FF6384"
]
}]
};
var ctx = $('#chart-area').get(0).getContext("2d");
var myDoughnutChart = new Chart(ctx, {
type: 'doughnut',
data: data,
animation: true,
responsive: true,
showTooltips: false,
percentageInnerCutout: 70,
segmentShowStroke: false,
onAnimationComplete: function () {
var canvasWidthvar = $('#chart-area').width();
var canvasHeight = $('#chart-area').height();
var constant = 114;
var fontsize = (canvasHeight / constant).toFixed(2);
//ctx.font="2.8em Verdana";
ctx.font = fontsize + "em Verdana";
ctx.textBaseline = "middle";
var total = 0;
$.each(data, function () {
total += parseInt(this.value, 10);
});
var tpercentage = ((data[0].value / total) * 100).toFixed(2) + "%";
console.log(total);
var textWidth = ctx.measureText(tpercentage).width;
var txtPosx = Math.round((canvasWidthvar - textWidth) / 2);
ctx.fillText(tpercentage, txtPosx, canvasHeight / 2);
}
});
});
I wanted to do it after animation finished and used onAnimationComplete function but onAnimationComplete function doesn't work here.
Upvotes: 3
Views: 5916
Reputation: 111
Faced same problem. Use onComplete() in options.animation instead:
options:{
animation:{
onComplete : function(){
/*Your code here*/
}
}
}
Upvotes: 11