Reputation: 31
I have used the chart.js 1.0.2 without knowing that a version 2+ arrived. Now I need fuctionallity only available in 2+ Meanwhile i have written several extensions to the chart.js 1.0.2 that i would like to convert to version 2+.
Chart.types.Doughnut.extend(
{
name: "DoughnutWithText",
draw: function() {
Chart.types.Doughnut.prototype.draw.apply(this, arguments);
width = this.chart.width,
height = this.chart.height;
var fontSize = (height / this.options.textScale).toFixed(2);
this.chart.ctx.font = fontSize + "em Lato";
this.chart.ctx.textBaseline = "middle";
this.chart.ctx.fillStyle="#000";
textX = Math.round((width - this.chart.ctx.measureText(this.options.doughnutText).width) / 2),
textY = height / 2;
this.chart.ctx.fillText(this.options.doughnutText, textX, textY);
}
});
How do I do do this in version 2+?
https://jsfiddle.net/64106xh8/1/
Upvotes: 3
Views: 2672
Reputation: 41065
With 2.1.x, you can write a plugin to do this
Preview
Script
Chart.pluginService.register({
afterDraw: function (chart) {
if (chart.config.options.elements.center) {
var helpers = Chart.helpers;
var centerX = (chart.chartArea.left + chart.chartArea.right) / 2;
var centerY = (chart.chartArea.top + chart.chartArea.bottom) / 2;
var ctx = chart.chart.ctx;
ctx.save();
var fontSize = helpers.getValueOrDefault(chart.config.options.elements.center.fontSize, Chart.defaults.global.defaultFontSize);
var fontStyle = helpers.getValueOrDefault(chart.config.options.elements.center.fontStyle, Chart.defaults.global.defaultFontStyle);
var fontFamily = helpers.getValueOrDefault(chart.config.options.elements.center.fontFamily, Chart.defaults.global.defaultFontFamily);
var font = helpers.fontString(fontSize, fontStyle, fontFamily);
ctx.font = font;
ctx.fillStyle = helpers.getValueOrDefault(chart.config.options.elements.center.fontColor, Chart.defaults.global.defaultFontColor);
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(chart.config.options.elements.center.text, centerX, centerY);
ctx.restore();
}
},
})
and then
...
options: {
elements: {
center: {
text: 'Hello',
fontColor: '#000',
fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
fontSize: 24,
fontStyle: 'normal'
}
}
}
};
Fiddle - http://jsfiddle.net/a1r1kszb/
Upvotes: 5