How to add text inside the doughnut chart using Chart.js?

137

Here is cleaned up and combined example of above solutions – responsive (try to resize the window), supports animation self-aligning, supports tooltips

https://jsfiddle.net/cmyker/u6rr5moq/

<html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>
<body>
    <canvas id="myChart"></canvas>
</body>
</html>

Chart.types.Doughnut.extend({
    name: "DoughnutTextInside",
    showTooltip: function() {
        this.chart.ctx.save();
        Chart.types.Doughnut.prototype.showTooltip.apply(this, arguments);
        this.chart.ctx.restore();
    },
    draw: function() {
        Chart.types.Doughnut.prototype.draw.apply(this, arguments);

        var width = this.chart.width,
            height = this.chart.height;

        var fontSize = (height / 114).toFixed(2);
        this.chart.ctx.font = fontSize + "em Verdana";
        this.chart.ctx.textBaseline = "middle";

        var text = "82%",
            textX = Math.round((width - this.chart.ctx.measureText(text).width) / 2),
            textY = height / 2;

        this.chart.ctx.fillText(text, textX, textY);
    }
});

var data = [{
    value: 30,
    color: "#F7464A"
}, {
    value: 50,
    color: "#E2EAE9"
}, {
    value: 100,
    color: "#D4CCC5"
}, {
    value: 40,
    color: "#949FB1"
}, {
    value: 120,
    color: "#4D5360"
}];

var DoughnutTextInsideChart = new Chart($('#myChart')[0].getContext('2d')).DoughnutTextInside(data, {
    responsive: true
});


UPDATE 17.06.16:

Same functionality but for chart.js version 2:

https://jsfiddle.net/cmyker/ooxdL2vj/

var data = {
  labels: [
    "Red",
    "Blue",
    "Yellow"
  ],
  datasets: [
    {
      data: [300, 50, 100],
      backgroundColor: [
        "#FF6384",
        "#36A2EB",
        "#FFCE56"
      ],
      hoverBackgroundColor: [
        "#FF6384",
        "#36A2EB",
        "#FFCE56"
      ]
    }]
};

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

var chart = new Chart(document.getElementById('myChart'), {
  type: 'doughnut',
  data: data,
  options: {
  	responsive: true,
    legend: {
      display: false
    }
  }
});


<script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.bundle.js"></script>
<canvas id="myChart"></canvas>

 


 

说点什么

892 评论 在 "How to add text inside the doughnut chart using Chart.js?"

提醒
排序:   最新 | 最旧 | 得票最多

没什么好说的,提前祝博主新年快乐!

需要向博主学习的地方还有很多,很多,很多……

Jajajajaj vaya LerKreL, no he estado por esas tierras, pero si dices que lo has vio3&s#82t0; Igual sí que es cosa del mar, oye… XDDDDDDDDDD ¿Las mariscadas en la playa?

ich beglГјckwГјnsche, der bemerkenswerte Gedanke
fatimaml

Hi, I think your website might be having browser compatibility issues. When I look at your blog in Safari, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, fantastic blog!
maxwellml

除了膜拜,别无它言!

Que entretenido topic
keyml

Incroyablement!
eaglesml

Found cat didn’t know what to call it. Found here exotic cat names http://allcatsnames.com/exotic-kitten-names full list of names for cats.

6cngsA It as nice to come across a blog every once in a while that isn at the

8t1w4R Really wonderful information can be found on web blog.

GoHmj1 It was hard It was hard to get a grip on everything, since it was impossible to take in the entire surroundings of scenes.

NT9Bhk Spot on with this write-up, I actually believe this site needs far more attention. I all probably be returning to see more, thanks for the advice!

oaB7Ai Terrific work! This is the type of information that are supposed to be shared across the web. Disgrace on Google for not positioning this post higher! Come on over and visit my web site. Thanks =)

NnaouA So content to get discovered this submit.. indeed, investigation is paying off. Enjoy the blog you furnished.. Good opinions you might have here..

Im obliged for the article post.Thanks Again. Cool. porno gifs

Not many will think of Davis as the best of my possibilities, beyond my own shortcomings and biases.

You made some really good points there. I checked on the internet for additional information about the issue and found most individuals will go along with your views on this website.

There as noticeably a bundle to find out about this. I assume you made certain nice factors in features also.

Very good info. Lucky me I discovered your blog by accident (stumbleupon). I have saved as a favorite for later!

It agree, it is the remarkable information

Some truly good content about this web website, appreciate it for info. A conservative can be a man which sits and also thinks, mostly sits. by Woodrow Wilson.

It抯 hard to find educated folks on this subject, however you sound like you recognize what you抮e talking about! Thanks

After I initially commented I clicked the -Notify me when new feedback are added- checkbox and now each time a remark is added I get four emails with the same comment. Is there any approach you possibly can take away me from that service? Thanks!

Well I really liked reading it. This post provided by you is very constructive for good planning.

I think you have mentioned some very interesting points, thankyou for the post.

This very blog is definitely interesting and besides factual. I have discovered a bunch of interesting tips out of this blog. I ad love to visit it again soon. Thanks!

Wohh exactly what I was looking for, thanks for putting up.

Incredible points. Solid arguments. Keep up the great effort.

Nice post. I learn something new and challenging on blogs I stumbleupon everyday. It as always useful to read through content from other authors and practice something from other web sites.

Whats up very nice website!! Man.. Excellent..

What kind of digicam did you use? That is certainly a decent premium quality.

I truly appreciate this post. I have been looking all over for this! Thank goodness I found it on Google. You have made my day! Thank you again.

This is very interesting, You are a very skilled blogger. I have joined your feed and look forward to seeking more of your great post. Also, I ave shared your web site in my social networks!

What as up, how as it going? Just shared this post with a colleague, we had a good laugh.

This blog was how do you say it? Relevant!! Finally I ave found something that helped me. Appreciate it!

Pretty! This has been an incredibly wonderful post. Many thanks

Would you be enthusiastic about exchanging links?

wow, awesome article post.Thanks Again. Fantastic.

I will immediately snatch your rss feed as I can at in finding your e-mail subscription hyperlink or e-newsletter service. Do you have any? Kindly let me know in order that I could subscribe. Thanks.

Thanks so much for the article. Really Great.

My brother suggested I might like this blog. He was entirely right. This post truly made my day. You cann at imagine simply how much time I had spent for this information! Thanks!

Looking forward to reading more. Great blog article.Much thanks again. Great.

My brother suggested I may like this web site. He was totally right. This submit actually made my day. You cann’t believe just how much time I had spent for this info! Thank you!
haidenml

I truly appreciate this blog.Thanks Again. Really Great.

Major thanks for the article post.Much thanks again. Great.

This is very interesting, You are a very skilled blogger. I have joined your feed and look forward to seeking more of your great post. Also, I ave shared your web site in my social networks!

Im thankful for the blog article. Really Cool.

This awesome blog is really awesome and besides amusing. I have discovered helluva handy advices out of this amazing blog. I ad love to return over and over again. Thanks a bunch!

wpDiscuz