[Chartjs]-Charts.js: thin donut chart background

2👍

You can extend the Doughnut chart to do this, like so

Chart.types.Doughnut.extend({
    name: "DoughnutAlt",
    initialize: function (data) {
        // call the actual initialize
        Chart.types.Doughnut.prototype.initialize.apply(this, arguments);

        // save the actual clear method
        var originalClear = this.clear;
        // override the clear method to draw the background after each clear
        this.clear = function () {
            // call the original clear method first
            originalClear.apply(this, arguments)

            var ctx = this.chart.ctx;
            // use any one of the segments to get the inner and outer radius and center x and y
            var firstSegment = this.segments[0];
            // adjust 0.3 to increaase / decrease the width of the background
            var gap = (firstSegment.outerRadius - firstSegment.innerRadius) * (1 - 0.3) / 2;

            // draw the background
            ctx.save();
            ctx.fillStyle = "#EEE";
            ctx.beginPath();
            ctx.arc(firstSegment.x, firstSegment.y, firstSegment.outerRadius - gap, 0, 2 * Math.PI);
            ctx.arc(firstSegment.x, firstSegment.y, firstSegment.innerRadius + gap, 0, 2 * Math.PI, true);
            ctx.closePath();
            ctx.fill();
            ctx.restore();
        }
    }
});

You would call it like this

var pointsUsed = new Chart(pointsUsed_ctx).DoughnutAlt(pointsUsed, {
    ...

Fiddle – http://jsfiddle.net/7nfL1m7d/

Leave a comment