简体   繁体   中英

How to get bar chart width in pixel

i am using chartjs lastest version (2.6.0). I just have a simple question that I want to get each bar width but i can not find the answer anywhere. Could someone please help me. Thanks alot. Here is simple bar chart.

 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 } }] } } }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script> <canvas class="canvasChart" id="myChart"></canvas> 

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM