简体   繁体   English

当我使用图表 div 的样式属性设置高度时,Horizo​​ntalBar 图表显示在画布下方(Chart.js 2.9.4)

[英]HorizontalBar chart is displayed below canvas when I set height with style attribute for chart div (Chart.js 2.9.4)

If I set height with style attribute for chart div如果我使用样式属性为图表 div 设置高度

<div id="chartDiv" style="height: 100px; border: 1px solid red;"><canvas id="chart"></canvas></div>

chart is looking like that (chart is displayed below canvas):图表看起来像这样(图表显示在画布下方):

 var barChartData = { labels: [""], datasets: [{ label: "1", backgroundColor: "rgba(68,222,166,1)", barThickness: 50, data: [177] }, { label: "2", barThickness: 50, backgroundColor: "rgba(218, 65, 102, 1)", data: [170] } ] }; var optionsBar = { legend: false, title: { display: false }, scales: { xAxes: [{ stacked: true, display: false }], yAxes: [{ stacked: true, display: false }] } }; var ctx = document.getElementById("chart"); var myChart = new Chart(ctx, { type: 'horizontalBar', data: barChartData, options: optionsBar });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.min.js"></script> <body style="background-color: grey;"> <div id="chartDiv" style="height: 100px; border: 1px solid red;"><canvas id="chart"></canvas></div> </body>

How to fix that?如何解决?

It's showing like this because canvas's aspect ratio is changing automatically with window size but you've set your div to a specific height of 100px .它显示为这样是因为画布的纵横比会随着窗口大小自动变化,但您已将 div 设置为特定高度100px That's why canvas has placed outside of the div while window size is extending.这就是为什么画布在窗口大小扩展时放置在 div 之外的原因。 Just to get rid of that problem, set maintainAspectRatio: false in your option in this way:只是为了摆脱这个问题,以这种方式在您的选项中设置maintainAspectRatio: false

 var barChartData = { labels: [""], datasets: [{ label: "1", backgroundColor: "rgba(68,222,166,1)", barThickness: 50, data: [177] }, { label: "2", barThickness: 50, backgroundColor: "rgba(218, 65, 102, 1)", data: [170] } ] }; var optionsBar = { maintainAspectRatio: false, legend: false, title: { display: false }, scales: { xAxes: [{ stacked: true, display: false }], yAxes: [{ stacked: true, display: false }] } }; var ctx = document.getElementById("chart"); var myChart = new Chart(ctx, { type: 'horizontalBar', data: barChartData, options: optionsBar });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.min.js"></script> <body style="background-color: grey;"> <div id="chartDiv" style="height: 100px; border: 1px solid red;"><canvas id="chart"></canvas></div> </body>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM