How to add labels into Chart.js canvas plugin?

后端 未结 4 1086
猫巷女王i
猫巷女王i 2020-12-07 22:49

I\'m using the awesome plugin Chart.js, and I\'m trying to find the way of display labels within each percentage. So I googled it, and I found this pull: https://github.com/

4条回答
  •  执笔经年
    2020-12-07 23:08

    This one literally took hours and hours and I found a working solution.

    https://github.com/nnnick/Chart.js/pull/116

    This was my final code. I was trying to display percentages as labels on doughnut

    Chart.types.Doughnut.extend({
    name: "DoughnutAlt",
    draw: function() {
        Chart.types.Doughnut.prototype.draw.apply(this, arguments);
        this.chart.ctx.fillStyle = 'black';
        this.chart.ctx.textBaseline = 'middle';
        this.chart.ctx.textAlign = 'start';
        this.chart.ctx.font="18px Verdana";
    
        var total = 0;
        for (var i = 0; i < this.segments.length; i++) { 
            total += this.segments[i].value;      
        }
    
        this.chart.ctx.fillText(total , this.chart.width / 2 - 20, this.chart.height / 2, 100);
        for(var i = 0; i < this.segments.length; i++){
            var percentage = ((this.segments[i].value / total) * 100).toFixed(1);
            if( percentage > 3 ){
                var centreAngle = this.segments[i].startAngle + ((this.segments[i].endAngle - this.segments[i].startAngle) / 2),
                    rangeFromCentre = (this.segments[i].outerRadius - this.segments[i].innerRadius) / 2 + this.segments[i].innerRadius;
                var x = this.segments[i].x + (Math.cos(centreAngle) * rangeFromCentre);
                var y = this.segments[i].y + (Math.sin(centreAngle) * rangeFromCentre);
                this.chart.ctx.textAlign = 'center';
                this.chart.ctx.textBaseline = 'middle';
                this.chart.ctx.fillStyle = '#fff';
                this.chart.ctx.font = 'normal 10px Helvetica';
                this.chart.ctx.fillText(percentage , x, y);
            }
         }
    }
    });
    

提交回复
热议问题