charts - 如何为响应式站点动态调整 chart.js 图形的大小?
问题描述
嘿,我知道这已经以一种或另一种方式回答了很多次,但我真的无法让它在我的 flex-box 上下文中工作。
我有固定的元素,例如页面上的页眉和页脚,以及一个占据中间所有剩余空间的图表。虽然乍一看似乎可以正常工作,但您可以看到文本和数字在调整窗口大小时变得模糊且未正确缩放。
我该如何解决这个问题,或者让 chart.js 在调整大小时重绘画布?
看看我的小提琴 https://jsfiddle.net/fg9pd1b3/
<body>
<div class="container">
<div class="fixed">
header
</div>
<div id="chartcontainer">
<canvas id="chartJSContainer"></canvas>
</div>
<div class="fixed">
footer
</div>
</div>
</body>
CSS:
html,
body {
height: 100vh;
min-height: 100vh;
max-height: 100vh;
margin: 0;
padding: 0;
}
.container {
width: 80%;
height: 100%;
margin: 0 auto;
display: flex;
flex-direction: column;
flex-basis: 100%;
flex-grow: 1;
background: #CCC;
}
.p {
text-align: center;
font-size: 14px;
padding-top: 140px;
}
.fixed {
background: black;
height: 100px;
min-height: 100px;
color: white;
text-align: center;
}
#chartcontainer {
position: relative;
min-height: 200px;
display: flex;
flex-grow: 1;
}
canvas {
width: 100% !important;
height: 100% !important;
}
JS:
Chart.defaults.global.responsive = true;
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderWidth: 1
}
]
},
options: {
scales: {
yAxes: [{
ticks: {
reverse: false
}
}]
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
解决方案
您已为画布 div 提供了固定的最小高度,这限制了图表进一步更改其尺寸。因此,以下代码自动将高度和宽度自动设置为 100%,从而提供灵活的图表。
#chartcontainer {
position:relative;
min-height:auto;
width:100%;
display: flex;
flex-grow:1;
}
推荐阅读
- c# - SQL Server 中日期的数据类型是什么?
- sql - 未能将窗口调用分解为组。至少 1 个组必须仅依赖于输入列
- python - 树莓派上的pydrive
- arrays - 将 label.textValue.last 与字符串数组进行比较
- swift - 在 XML 数据上创建 CMS 签名时崩溃
- firebase - 在 Firestore 中的不同字段上涉及 isGreaterThan 或 isLessThan 的多个查询
- python - 为划分为 bin 的数据绘制箱须图
- sql - 在SQL中选择字符串中每个单词的第一个字母
- python - Gensim word2vec 训练不会在批处理结束时回调
- python - 如何处理“仅对唯一值索引对象有效的重新索引”