如何使用chart.js在环形图的中心添加文本
How to add text in centre of the doughnut chart using Chart.js?
我想创建一个有两个值的圆环图。单击图形应在中心打印值。我在stackoverflow中找到了一个与我的要求类似的解决方案。我想使用github的最新Chart.js库。这个功能在最新的Chart.js中可用吗?
在Chart.js v2.x 中这样做当然是可能的
我认为最好的方法是使用插件。事实上,Cmyker回答了你链接到的问题,甚至更新了他的帖子,展示了这在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();
}
});
您还可以向配置中添加一个参数,并将其用作文本:
"options": {
title: {
display: true,
position: "bottom",
text: 'Upcoming Meetings'
},
legend: {
display: false
},
centertext: "123"
}
javascript看起来类似于此(请注意:甜甜圈有一个标题,但没有图例,定位居中的文本在某种程度上是在试验):
<script>
Chart.pluginService.register({
beforeDraw: function (chart) {
if (chart.options.centertext) {
var width = chart.chart.width,
height = chart.chart.height,
ctx = chart.chart.ctx;
ctx.restore();
var fontSize = (height / 80).toFixed(2); // was: 114
ctx.font = fontSize + "em sans-serif";
ctx.textBaseline = "middle";
var text = chart.options.centertext, // "75%",
textX = Math.round((width - ctx.measureText(text).width) / 2),
textY = height / 2 - (chart.titleBlock.height - 15);
ctx.fillText(text, textX, textY);
ctx.save();
}
}
});
</script>
David的回答非常有效。谢谢我想补充一点,文本并没有真正集中,因为它没有考虑到图例的高度。
var legendHeight = chart.legend.height;
textY = height / 2 + legendHeight/2;
添加这些会解决这个问题。
这是最新版本的ChartJs(07/23/2021)
我自定义了插件以使其工作——我无法通过复制和粘贴使其工作。当我开始工作时,除以1.87。
let textY = height / 2
->let textY = height / 1.87
const centerDoughnutPlugin = {
id: "annotateDoughnutCenter",
beforeDraw: (chart) => {
let width = chart.width;
let height = chart.height;
let ctx = chart.ctx;
ctx.restore();
let fontSize = (height / 114).toFixed(2);
ctx.font = fontSize + "em sans-serif";
ctx.textBaseline = "middle";
let text = "75%";
let textX = Math.round((width - ctx.measureText(text).width) / 2);
let textY = height / 1.87;
console.log("text x: ", textX);
console.log("text y: ", textY);
ctx.fillText(text, textX, textY);
ctx.save();
},
};
// Register Donut Plugin
Chart.register(centerDoughnutPlugin);
相关文章:
- 在highcharts.js中向点弹出窗口动态添加文本
- 向d3圆添加文本
- 如何在已经有图标的滚动到顶部按钮中添加文本
- 如何在背景图像上添加文本
- 如何使用javascript在asp.net网页表单上动态添加文本框
- 如何从DIV数组向DIV添加文本
- 我可以通过javascript在鼠标光标旁边动态添加文本吗?
- 如何使用 jQuery 在文本区域中的每一行添加文本
- 单击向输入添加文本值的链接
- 使用.html()添加文本输入时出现意外行为
- 在d3.js中添加文本标签以强制定向图链接
- 当我尝试添加文本效果时,有东西阻止了JavaScript的运行'手风琴'在html文档中
- 在每个条形图的中间添加文本标签&鼠标悬停事件
- 通过在 JavaScript 中使用正文标签的 ID 向
标签添加文本
- JavaScript在段落中的页面加载后添加文本
- eventListner,用于在另一个文本框获得焦点时添加文本框(vanilla-js)
- 如何根据复选框在输入中添加文本
- Bootstrap 3通过点击按钮添加文本并显示在新选项卡中
- 用户动态添加文本框时,文本框中的echo值
- jqueryTe正在添加文本