[Chartjs]-How to get the length (height) of the vertical bar in Chart.js

0👍

Try using getDatasetMeta() to get the metadata.

var meta = myChart.getDatasetMeta(0);
var height = meta.data[0]._model.height;

0👍

The origin (value zero) of the y-axis is at the top of the canvas. Therefore, you need to subtract the value obtained through yAxis.getPixelForValue(value) from yAxis.bottom as follows:

afterLayout: chart => {      
  var yAxis = chart.scales['y-axis-0']; 
  chart.data.datasets[0].data.forEach(value => {
    console.log(Math.round(yAxis.bottom - yAxis.getPixelForValue(value))); 
  });      
}

Please take a look at below sample and see how it works (code is derived from the Chart.js Bar documentation page).

new Chart('myChart', {
  type: "bar",
  plugins: [{
    afterLayout: chart => {      
      var yAxis = chart.scales['y-axis-0']; 
      chart.data.datasets[0].data.forEach(value => {
        console.log(Math.round(yAxis.bottom - yAxis.getPixelForValue(value))); 
      });      
    }
  }],
  data: {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [{
      label: "My First Dataset",
      data: [65, 59, 80, 81, 56, 55, 40],
      fill: false,
      backgroundColor: ["rgba(255, 99, 132, 0.2)", "rgba(255, 159, 64, 0.2)", "rgba(255, 205, 86, 0.2)", "rgba(75, 192, 192, 0.2)", "rgba(54, 162, 235, 0.2)", "rgba(153, 102, 255, 0.2)", "rgba(201, 203, 207, 0.2)"],
      borderColor: ["rgb(255, 99, 132)", "rgb(255, 159, 64)", "rgb(255, 205, 86)", "rgb(75, 192, 192)", "rgb(54, 162, 235)", "rgb(153, 102, 255)", "rgb(201, 203, 207)"],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          min: 0,
          stepSize: 20
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="myChart" height="90"></canvas>

Leave a comment