How to add labels into Chart.js canvas plugin?

后端 未结 4 1034
猫巷女王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:16

    I have figured out a way so that we can display the values for each region out side the graph.

    Also I removed the rotation of the values and I referred to here

    Add the following lines of code inside the Doughnut function. ( I have pasted the modified lines from the Chart.js file).

        var Doughnut = function(data,config,ctx){
    
        var segmentTotal = 0;
    
        //In case we have a canvas that is not a square. Minus 10 pixels as padding round the edge.
        var doughnutRadius = Min([height/2,width/2]) - 15;
        var cutoutRadius = doughnutRadius * (config.percentageInnerCutout/100);
        //Modified for setting the label values out side the arc
        var outRadius= doughnutRadius + cutoutRadius/3;
        var outRadiustop= doughnutRadius + cutoutRadius/5;
        ......
        ......
        ......
    
        function drawPieSegments (animationDecimal){
        :
        :
    
    
    
           if (config.scaleShowValues) {
                    ctx.save();                
                    ctx.translate(width / 2, height / 2);
                    ctx.font = config.scaleFontStyle + ' ' + config.scaleFontSize + 'px ' + config.scaleFontFamily;
                    ctx.textBaselne = 'middle';
                    var a = (cumulativeAngle + cumulativeAngle + segmentAngle) / 2,
                        w = ctx.measureText(data[i].value).width,
                        b = Math.PI / 2 < a && a < Math.PI * 3 / 2;
                    var c  = 0 < a && a < Math.PI;
                    if(b){
                        ctx.textAlign = 'right';
                    }
                    else{
                        ctx.textAlign = 'left';
                    }
                    if(c){
                        ctx.translate(Math.cos(a) * outRadius +1 , Math.sin(a) * outRadius+1);
    
                    }
                    else{
                        ctx.translate(Math.cos(a) * outRadiustop, Math.sin(a) * outRadiustop);      
                    }
    
                    ctx.fillStyle = config.scaleFontColor;
                    //If the segment angle less than 0.2, then the lables will overlap, so hiding it.
                    if(segmentAngle > 0.2){
                        ctx.fillText(data[i].value,0,0);
    
                    }
                    ctx.restore();
         }
    
         ......
         ...... 
    

    Now the values will be displayed out side each sections and it will not be rotated.

提交回复
热议问题