我想用Chart.js绘制一个水平条形图,但它一直在缩放图表,而不是使用我在脚本中为画布指定的高度。
有没有办法从脚本中设置图形的高度?
请参阅小提琴:Jsfidle
HTML
<div class="graph">
<div class="chart-legend">
</div>
<div class="chart">
<canvas id="myChart"></canvas>
</div>
</div>
JavaScript
var ctx = $('#myChart');
ctx.height(500);
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
maintainAspectRatio: false,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
发布于 2017-01-31 16:59:28
看起来像是var ctx = $('#myChart');
返回了一个元素列表。您需要使用ctx[0]
引用第一个。另外,高度是一个属性,而不是一个函数。
我在我的代码中是这样做的:
var chartEl = document.getElementById("myChart");
chartEl.height = 500;
发布于 2017-04-27 20:56:07
如果禁用选项中的保持纵横比,则它将使用可用高度:
var chart = new Chart('blabla', {
type: 'bar',
data: {
},
options: {
maintainAspectRatio: false,
}
});
发布于 2018-01-30 22:22:45
最简单的方法是为画布创建一个容器并设置其高度:
<div style="height: 300px">
<canvas id="chart"></canvas>
</div>
和set
options: {
responsive: true,
maintainAspectRatio: false
}
https://stackoverflow.com/questions/41953158
复制相似问题