如何使用 Chart.js 在圆环图的中心添加文本? [英] How to add text in centre of the doughnut chart using Chart.js?
问题描述
我想创建一个具有两个值的甜甜圈图.单击图形应在中心打印值.我在 stackoverflow 中找到了解决方案类似于我的要求.我想使用来自 github 的最新 Chart.js 库.此功能在最新的 Chart.js 中可用吗?
I want to create a Doughnut graph with two values. Clicking the graphs should print the value in center. I found a solution in stackoverflow similar to my requirement. I would like to use latest Chart.js library from github. Is this feature is available in latest Chart.js?
推荐答案
在 Chart.js v2.x 中当然可以做这样的事情
It is certainly possible to do something like this in Chart.js v2.x
我认为最好的方法是使用插件.事实上,Cmyker awnser你链接的问题甚至更新了他的帖子,以展示这在 Charts.js v2.x 中的工作原理
I think the nicest way to do it is by using a plugin. In fact, Cmyker awnser to the question you linked to even updated his posts to show how this would work in Charts.js v2.x
看他的小提琴:https://jsfiddle.net/cmyker/ooxdL2vj/
以及对应的插件定义:
Chart.pluginService.register({
beforeDraw: function(chart) {
var width = chart.chart.width,
height = chart.chart.height,
ctx = chart.chart.ctx;
ctx.restore();
var fontSize = (height / 114).toFixed(2);
ctx.font = fontSize + "em sans-serif";
ctx.textBaseline = "middle";
var text = "75%",
textX = Math.round((width - ctx.measureText(text).width) / 2),
textY = height / 2;
ctx.fillText(text, textX, textY);
ctx.save();
}
});
这篇关于如何使用 Chart.js 在圆环图的中心添加文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!