B.V.S Bharat Kumar
B.V.S Bharat Kumar

Reputation: 222

how to align count text center in horizontal bar in the Chart.js?

I tried with dividing the graph bar value into half part but it's not working!

Code link

enter image description here

Chart.helpers.each(
            meta.data.forEach(function(bar, index) {
              data = dataset.data[index];
              if (i == 0) {
                ctx.fillText(data, bar._model.x/1.6, bar._model.y + 4);
              } else {
                ctx.fillText(data, bar._model.x-25, bar._model.y + 4);
              }
            }),

Upvotes: 1

Views: 3158

Answers (1)

ɢʀᴜɴᴛ
ɢʀᴜɴᴛ

Reputation: 32879

You can get the center position of each horizontal bar (inside meta.data loop) as follows :

var barWidth = bar._model.x - bar._model.base;
var centerX = bar._model.base + barWidth / 2;

and after getting the position, draw the count text accordingly...

Chart.helpers.each(this.data.datasets.forEach(function(dataset, i) {
   var meta = chartInstance.controller.getDatasetMeta(i);
   Chart.helpers.each(meta.data.forEach(function(bar, index) {
      var data = dataset.data[index];
      var barWidth = bar._model.x - bar._model.base;
      var centerX = bar._model.base + barWidth / 2;
      if (i == 0) {
         ctx.fillText(data, centerX, bar._model.y + 4);
      } else {
         ctx.fillText(data, centerX, bar._model.y + 4);
      }
   }), this);
}), this);

see - live demo

Upvotes: 2

Related Questions