如何调整ChartJS散点图尺寸以匹配PDF规格?
解决ChartJS散点图显示压缩问题
首先看你的代码,有两个关键问题导致图表被压缩:
1. CSS尺寸缺少单位
你的.test类中max-width: 400和height: 225没有指定单位(应该是px),浏览器无法正确解析容器尺寸,导致图表布局异常。
2. ChartJS响应式配置不合理
默认情况下responsive: true且maintainAspectRatio: true,图表会强制保持默认宽高比,即使你设置了容器高度,也会被这个规则覆盖,导致图表被压缩。
修改后的完整代码:
CSS部分:
.container { display: flex; justify-content: center; align-items: center; } .test { width: 100%; max-width: 400px; /* 补充px单位 */ height: 225px; /* 补充px单位 */ }
JS部分:
document.addEventListener("DOMContentLoaded", function () { var envelope = {{{envelopeJSON}}}; var utility = {{{utilityJSON}}}; var mb = {{{mbJSON}}}; new Chart("myChart", { type: "scatter", data: { datasets: [ { label: "{{airplanename}}", pointRadius: 4, pointBackgroundColor: "rgb(0, 0, 255)", data: envelope, showLine: true, fill: true, borderColor: "rgb(0, 150, 255)", backgroundColor: "rgba(0, 0, 255, 0.2)" }, { label: "Utility", pointRadius: 4, pointBackgroundColor: "rgb(255, 36, 0)", data: utility, showLine: true, fill: true, borderColor: "rgba(255, 36, 0, 0.5)", backgroundColor: "rgba(255, 36, 0, 0.2)" }, { label: "Data", pointRadius: 4, pointBackgroundColor: "rgb(0, 0, 255)", data: mb, showLine: true, borderColor: "rgb(0, 150, 255)", } ] }, options: { responsive: true, // 开启响应式,适配容器尺寸 maintainAspectRatio: false, // 关闭强制宽高比,让容器高度生效 legend: { display: false }, scales: { xAxes: [{ ticks: { min: 80, max: 90 } }], yAxes: [{ ticks: { min: 1000, max: 2500 } }], } } }); });
关键说明:
- 补充CSS单位后,容器的宽高会被浏览器正确识别,为图表提供固定的渲染区域。
responsive: true让图表跟随容器尺寸变化,maintainAspectRatio: false允许图表突破默认宽高比,完全适配你设置的容器高度,避免压缩变形。- 如果后续需要调整图表尺寸,直接修改
.test类的max-width和height即可,无需改动ChartJS配置。
内容的提问来源于stack exchange,提问作者pilotflows
相关产品推荐
相关产品推荐

