我正在尝试使用 Chart.js 开发一些 donut chart 形,但我不知道如何在图形内部写入以及如何使图形更薄。
这是我用 javascript 开发的:
var config = {
type: 'doughnut',
data: {
datasets: [{
data: [
data.VSTPS_OEEDATOF[0].PctOEE,
"100" - data.VSTPS_OEEDATOF[0].PctOEE,
],
backgroundColor: [
"#979494",
"#FFFFFF",
],
}]
},
options: {
responsive: true,
}
};
var ctx = document.getElementById("chart-area").getContext("2d");
window.myDoughnut = new Chart(ctx, config);
这是我的 html:
<div id="canvas-holder" style="width:18%">
<canvas id="chart-area" />
</div>
这是运行后的样子:
有人可以帮助我吗?
谢谢您的建议!
最佳答案
如果有人想知道我如何解决这个问题,这里是如何解决的:
我只是将以下插件添加到我的 js 代码中:
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);
}
}
});
并在图表配置内的选项部分添加元素“element”:
options: {
responsive: true,
elements: {
center: {
text: '50%',
fontStyle: 'Roboto',
sidePadding: 20
}
},
tooltips: {
enabled: false
}
}
};
就这些了!
关于javascript - 使用chart.js绘制图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47332979/