简体   繁体   English

如何以像素为单位获取条形图宽度

[英]How to get bar chart width in pixel

i am using chartjs lastest version (2.6.0). 我正在使用chartjs最新版本(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. 你可以在每个ChartJS条宽度(基本一致),.getDatasetMeta()方法。

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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