我想将我的数据值的文本放置在chart js圆环图的中心,我不知道该怎么做,我检查了chart js官方文档,但他们没有提供任何有关此的信息,怎么办我实现了这一点。
这是我的代码:
HTML:
<canvas id="gx_150s_658Ed8745321" width="200" height="120"></canvas>
Run Code Online (Sandbox Code Playgroud)
JS:
var randomScalingFactor = function () {
return Math.round(Math.random() * 100);
};
var gx_150s_658Ed8745321_ctx = document.getElementById('gx_150s_658Ed8745321').getContext('2d');
var gx_150s_658Ed8745321 = new Chart(gx_150s_658Ed8745321_ctx, {
type: 'doughnut',
data: {
labels: ['Utilized', 'Balence'],
datasets: [{
label: 'Utilized',
data: [95, 5],
backgroundColor: [
'rgb(0, 153, 0, 0.7)',
],
borderColor: [
'rgba(54, 162, 235, 2)',
],
borderWidth: 1
}]
},
options: {
legend: {
display: false
},
title: {
display: true,
text: ' Utilized : 95 %'
},
animation: {
animateScale: true,
animateRotate: true
},
}
});
Run Code Online (Sandbox Code Playgroud)
预期输出:
小智 5
我正在使用一个简单的插件:
config = {
options: {
//...
}
//...
plugin: [{
id: 'my-doughnut-text-plugin',
afterDraw: function (chart, option) {
let theCenterText = "50%" ;
const canvasBounds = canvas.getBoundingClientRect();
const fontSz = Math.floor( canvasBounds.height * 0.10 ) ;
chart.ctx.textBaseline = 'middle';
chart.ctx.textAlign = 'center';
chart.ctx.font = fontSz+'px Arial';
chart.ctx.fillText(theCenterText, canvasBounds.width/2, canvasBounds.height*0.70 )
}
}];
}
Run Code Online (Sandbox Code Playgroud)
您仍然需要计算中心文本中不需要的内容(变量 theCenterText)。