Created
December 10, 2017 08:35
-
-
Save TranBaVinhSon/0d3719d0c8e3f9d93eb0265ffbf2a3b6 to your computer and use it in GitHub Desktop.
Text inside Doughnut Chart.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Chart.pluginService.register({ | |
beforeDraw: function (chart) { | |
if (chart.config.options.elements.center) { | |
//Get ctx from string | |
var ctx = chart.chart.ctx; | |
//Get options from the center object in options | |
var centerConfig = chart.config.options.elements.center; | |
var fontStyle = centerConfig.fontStyle || 'Arial'; | |
var txt = centerConfig.text; | |
var color = centerConfig.color || '#000'; | |
var sidePadding = centerConfig.sidePadding || 20; | |
var sidePaddingCalculated = (sidePadding/100) * (chart.innerRadius * 2) | |
//Start with a base font of 30px | |
ctx.font = "30px " + fontStyle; | |
//Get the width of the string and also the width of the element minus 10 to give it 5px side padding | |
var stringWidth = ctx.measureText(txt).width; | |
var elementWidth = (chart.innerRadius * 2) - sidePaddingCalculated; | |
// Find out how much the font can grow in width. | |
var widthRatio = elementWidth / stringWidth; | |
var newFontSize = Math.floor(30 * widthRatio); | |
var elementHeight = (chart.innerRadius * 2); | |
// Pick a new font size so it will not be larger than the height of label. | |
var fontSizeToUse = Math.min(newFontSize, elementHeight); | |
//Set font settings to draw it correctly. | |
ctx.textAlign = 'center'; | |
ctx.textBaseline = 'middle'; | |
var centerX = ((chart.chartArea.left + chart.chartArea.right) / 2); | |
var centerY = ((chart.chartArea.top + chart.chartArea.bottom) / 2); | |
ctx.font = fontSizeToUse+"px " + fontStyle; | |
ctx.fillStyle = color; | |
//Draw text in center | |
ctx.fillText(txt, centerX, centerY); | |
} | |
} | |
}); | |
// Option: | |
options: { | |
elements: { | |
center: { | |
text: '90%', | |
sidePadding: 60 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment