Chart.js设置horizontalBar图表高度为100%失败问题求助
Chart.js 高度无法设为100%的解决方案
问题出在配置参数规则和容器样式设置两个层面,按以下步骤修改即可:
- 第一步:调整Chart.js配置项
你当前配置中的maintainAspectRatio: true和aspectRatio: 1会强制图表宽高比固定为1:1,直接限制了高度自适应,修改这两个参数即可:
type: 'horizontalBar', data: chartdata, options:{ responsive: true, maintainAspectRatio: false, // 将true改为false,关闭宽高比强制限制 // 直接删除aspectRatio: 1这一行,该参数仅在maintainAspectRatio为true时生效 animation: false, scaleSteps: 10, legend:{ display: false, }, showAllTooltips: true, tooltips:{ enabled: false, }, layout:{ padding:{ right: 70, } }, scales: { xAxes: [{ position: 'top', gridLines: { lineWidth: 1, }, scaleLabel: { display: true, labelString: 'Nombre de mouvement par outil', }, ticks: { min: 0, stepSize: 1, }, }], yAxes: [{ barPercentage:0.9, categoryPercentage:1, gridLines: { lineWidth: 1, }, scaleLabel: { display: true, labelString: 'Identifiants outils', }, }], }, }
- 第二步:给图表父容器设置高度基准
Chart.js响应式模式下的高度依赖外层容器的高度值,需要给包裹canvas的父元素设置明确高度:
/* 若需要图表占满整个父级区域,需要给所有上层容器都设置100%高度 */ html, body, .chart-wrapper { height: 100%; margin: 0; } /* 也可以直接给父容器设置固定高度 */ .chart-wrapper { width: 100%; height: 500px; }
如果是并排展示两张图表,给每张图表单独套一层父容器,分别设置高度即可避免互相影响。
- 可选补充:如果是动态渲染图表,初始化完成后可手动调用重绘方法适配容器:
const myChart = new Chart(canvasDom, config); myChart.resize();
内容的提问来源于stack exchange,提问作者sairus
相关产品推荐
相关产品推荐

