我正在尝试使用Chart.js文档中给出的示例代码。
画布元素上行内指定了宽度和高度为400px / 400px。
但是当渲染图表时,它会被放大到整个页面宽度,并且切掉最右边的部分。
我应该在哪里/如何控制图表的宽度/高度?
你可以重写画布的样式宽度 !important ...
canvas{
width:1000px !important;
height:600px !important;
}
还需在选项下指定responsive:true
属性。
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
更新选项中添加:maintainAspectRatio: false,
canvas{ width:100% !important; height:600px !important; }
和 maintainAspectRatio: false,
解决了我的问题。谢谢。 - Kamlesh根据官方文档(http://www.chartjs.org/docs/latest/general/responsive.html#important-note),您还可以简单地使用容器来包围图表
HTML
<div class="chart-container">
<canvas id="myCanvas"></canvas>
</div>
CSS
.chart-container {
width: 1000px;
height:600px
}
并带有选项
responsive: true
maintainAspectRatio: false
!important
才有效。 - Артур Гудиев在我的情况下,在选项下传递 responsive: false
解决了问题。我不确定为什么每个人都告诉你做相反的事情,特别是因为 true 是默认值。
注:原文中的代码标签已被保留。
responsive: true
设置为真完全扭曲了图表的外观。 - Paul!important
时才对我有效。 - Артур Гудиев我无法相信没有人提到使用相对定位的父元素。
代码:
<div class="chart-container" style="position: relative; height:40vh; width:80vw">
<canvas id="chart"></canvas>
</div>
来源:官方文档
width
和height
,不能像我一开始尝试的那样只设置height
。 - Chud37aspectRatio
:options:{
aspectRatio:4 //(width/height)
}
4
不是一个宽高比。你的评论中写着(width/height)
,但不清楚应该如何应用。有没有一种方法可以将其作为一组传递?或者你是真的意思是将建议的宽度除以建议的高度,例如3:4变成0.75
? - Jeremy Caneyoptions: {
responsive: true,
scales: {
yAxes: [{
display: true,
ticks: {
min:0,
max:100
}
}]
}
}
虽然上面没有提到,但在画布元素上使用max-width
或max-height
也是一种可能性。
var myChart = new Chart(ctx, {
type: 'line',
data: data,
options: {
maintainAspectRatio: false,
responsive:true,
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
使用这个,它很好用。
<canvas id="totalschart" style="height:400px;width: content-box;"></canvas>
并且在选项
下面,
responsive:true,
<div class="wrap">
<canvas id="myChart"></canvas>
</div>
.grafico{
width: 400px !important;
}
JS图表选项的任何更改
var myChart = new Chart(ctx, {
type: 'bar', //doughnut, bar, line, radar, pie, polarArea
data: data,
options: {
scales: {
y: {
beginAtZero: true,
stepSize: 1
}
}
},
});
};