[Chartjs]-Chart js – Get bar width after render

10👍

Usually you can use getDatasetMeta() method of the chart to get bar width.

However, if you were to change/update the point-radius of the line graph dynamically (on window resize), you would have to use a chart plugin, as such :

Chart.plugins.register({
   updated: false,
   beforeDraw: function(chart) {
      var barWidth = chart.getDatasetMeta(1).data[0]._model.width;
      var line = chart.data.datasets[0];
      line.pointRadius = barWidth / 2;
      line.pointHoverRadius = barWidth / 2;
      if (!this.updated) {
         chart.update();
         this.updated = true;
      }
   }
});

* add this at the beginning of your script

ᴅᴇᴍᴏ ⧩

Chart.plugins.register({
   updated: false,
   beforeDraw: function(chart) {
      var barWidth = chart.getDatasetMeta(1 /* dataset-index of bar graph */).data[0]._model.width;
      var line = chart.data.datasets[0 /* dataset-index of line graph */];
      line.pointRadius = barWidth / 2;
      line.pointHoverRadius = barWidth / 2;
      // update chart at first render with newly added values
      if (!this.updated) {
         chart.update();
         this.updated = true;
      }
   }
});

var chart = new Chart(ctx, {
   type: 'bar',
   data: {
      labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
      datasets: [{
         type: 'line',
         label: 'LINE',
         data: [3, 1, 4, 2, 5],
         backgroundColor: 'rgba(0, 119, 290, 0.5)',
         borderColor: 'transparent',
         pointBorderColor: '#07C',
         fill: false,
         pointStyle: 'line'
      }, {
         label: 'BAR',
         data: [3, 1, 4, 2, 5],
         backgroundColor: 'rgba(4, 142, 128, 0.5)'
      }]
   },
   options: {
      scales: {
         yAxes: [{
            ticks: {
               beginAtZero: true
            }
         }]
      }
   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx"></canvas>

Leave a comment