Inserting percentage charts.js doughnut

前端 未结 4 639
失恋的感觉
失恋的感觉 2021-02-06 08:39

i\'m, using charts.js librarie and would like to know how could I add some mark to the hole of a doughnut chart (sth like a percentage)-

4条回答
  •  广开言路
    2021-02-06 09:06

    Draw method creates the canvas for chart. On hover draw method is called to re-create the chart and show the tool-tip. Text disappears because there is no code to show text inside draw method as we are adding text manually outside of API.

    You can achieve this by extending the chart. Follow Docs here.

    Following is the example of adding total records at the centre of the doughnut chart.

    Chart.defaults.derivedDoughnut = Chart.defaults.doughnut;
    var customDoughnut = Chart.controllers.doughnut.extend({
      draw: function(ease) {
        Chart.controllers.doughnut.prototype.draw.apply(this, [ease]);
        var width = this.chart.chart.width,
          height = this.chart.chart.height;
        var total = this.getMeta().total;
        var fontSize = (height / 114).toFixed(2);
        var ctx = this.chart.chart.ctx;
        ctx.font = fontSize + "em Verdana";
        ctx.textBaseline = "middle";
        var text = total,
          textX = Math.round((width - ctx.measureText(text).width) / 2),
          textY = height / 2;
    
        ctx.fillText(text, textX, textY);
      }
    });
    Chart.controllers.derivedDoughnut = customDoughnut;
    

    Example: jsfiddle

提交回复
热议问题