How to add text in centre of the doughnut chart using Chart.js?

China☆狼群 提交于 2019-12-01 06:53:32
David

It is certainly possible to do something like this in Chart.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

See his fiddle: https://jsfiddle.net/cmyker/ooxdL2vj/

and the corresponding plugin definition:

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();
  }
});

You can also add a parameter to the configuration and use this as text:

    "options": {
        title: {
            display: true,
            position: "bottom",
            text: 'Upcoming Meetings'
        },
        legend: {
            display: false
        },
        centertext: "123"
    }

And the javascript would look similar to this (please note: doughnuts have a title but no legend, positioning the centered text was somehow experimenting):

    <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>

The answer by David works darn well. Thanks. I would like to add that the text is not really centralised as it did not take into account the legend height.

var legendHeight =  chart.legend.height;

textY = height / 2 + legendHeight/2;

Adding these will fix that.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!