我正在使用chartjs最新版本(2.6.0)。我只是有一个简单的问题,我想得到每个条宽,但我找不到任何答案。有人可以帮帮我吗非常感谢。这是简单的条形图。
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>
&#13;
答案 0 :(得分:1)
您可以使用.getDatasetMeta()
方法在ChartJS中获取每个条的 宽度(基本相同)。
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>