Chartjs-How to know the length of the horizontal bar in Chart.js

0👍

You can use the Plugin Core API. It offers different hooks that may be used for executing custom code. In below code snippet, I use the afterDraw hook to log the number of pixels of individual bars.

const chart = new Chart(document.getElementById('myChart'), {
  type: 'horizontalBar',
  plugins: [{
    afterDraw: chart => {      
      var ctx = chart.chart.ctx; 
      var xAxis = chart.scales['x-axis-0'];   
      chart.config.data.datasets[0].data.forEach((value, index) => {
        console.log('index ' + index + ': ' + Math.round(xAxis.getPixelForValue(value)) + 'px'); 
      });      
    }
  }],
  data: {
    labels: ['A', 'B', 'C', 'D'],
    datasets: [{
      label: 'By Dataset',
      data: [15, 8, 12, 18],
      backgroundColor: 'blue'
    }]
  },
  options: { 
    scales: {
      xAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]     
    }  
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="90"></canvas>

Leave a comment