Created
June 16, 2016 14:23
-
-
Save murilobr/2bfef8d1f28867ed80ea0f4ad8f0c247 to your computer and use it in GitHub Desktop.
Chart.js Gauge
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({ | |
afterDraw: function(chart) { | |
if (chart.config.options.elements.center) { | |
var helpers = Chart.helpers; | |
var ctx = chart.chart.ctx; | |
ctx.save(); | |
var width = (chart.chartArea.left + chart.chartArea.right), | |
height = (chart.chartArea.top + chart.chartArea.bottom); | |
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); | |
var fontSize = (chart.offsetY/1.8).toFixed(2); | |
var font = helpers.fontString(fontSize, fontStyle, fontFamily); | |
ctx.font = font; | |
ctx.textBaseline = 'middle'; | |
var text = chart.config.options.elements.center.text, | |
textX = Math.round((width - ctx.measureText(text).width) / 2), | |
textY; | |
var circumference = helpers.getValueOrDefault(chart.config.options.circumference, Chart.defaults.global.defaultCircumference); | |
if(circumference > Math.PI){ | |
textY = height / 2; | |
} else { | |
textY = ((height/2) + chart.offsetY)-(fontSize/2.3); | |
} | |
ctx.fillText(text, textX, textY); | |
ctx.restore(); | |
} | |
} | |
}); | |
var chart = new Chart(ctx, { | |
type: 'doughnut', | |
data: { | |
labels: data, | |
datasets: [ | |
{ | |
data: data, | |
backgroundColor: [ | |
"#FF6384" | |
] | |
} | |
] | |
}, | |
options: { | |
animation: false, | |
circumference: Math.PI, | |
rotation: Math.PI, | |
maintainAspectRatio: false, | |
legend: { | |
display: false | |
}, | |
legendCallback: function (chart) { return; }, | |
tooltips: { | |
enabled: false | |
}, | |
hover: { | |
mode: null | |
}, | |
elements: { | |
center: { | |
text: '', | |
fontColor: '#000', | |
fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", | |
fontStyle: 'normal' | |
} | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment