Chartjs-How to get bar chart width in pixel

1👍

You can get each bar­‘s width (basically the same) in ChartJS, using .getDatasetMeta() method.

var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
   type: 'bar',
   data: {
      labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
      datasets: [{
         label: '# of Votes',
         data: [12, 19, 3, 5, 2, 3]
      }]
   },
   options: {
      scales: {
         yAxes: [{
            ticks: {
               beginAtZero: true
            }
         }]
      }
   }
});

function getWidth() {
   var barWidth = myChart.getDatasetMeta(0).data[0]._view.width;
   alert(barWidth);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>

<button onclick="getWidth()">Get Bar Width</button>
<canvas class="canvasChart" id="myChart"></canvas>

Leave a comment