如何使用Chart.js在甜甜圈图的中心添加文本? [英] How to add text in centre of the doughnut chart using Chart.js?

查看:409
本文介绍了如何使用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遮阳篷您链接到的问题甚至更新了他的帖子,以显示在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆