"flex: 1 1 0%" 和 canvas child 调整其大小无法正常工作
"flex: 1 1 0%" with a canvas child that adapts its size is not working properly
以下示例创建页眉、canvas 和页脚。 canvas 被告知填充页眉和页脚之间的 space。发生以下情况:
- 扩大window:canvas增长
- 缩小window:出现滚动条,但我希望canvas缩小
为什么 canvas 没有收缩,我怎样才能让它收缩?
const canvas = document.getElementById("canvas");
function paint() {
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
const ctx = canvas.getContext("2d");
ctx.fillText(canvas.height, canvas.width / 2, canvas.height / 2);
}
paint();
new ResizeObserver(paint).observe(canvas);
.main {
height: 100%;
display: flex;
flex-flow: column;
}
.canvas {
flex: 1 0 0%;
}
html, body {
height: 100%;
margin: 0;
}
<div class="main">
<div class="header">
Header
</div>
<canvas id="canvas" class="canvas"></canvas>
<div class="footer">
Footer
</div>
</div>
将 canvas
高度设置为 0 并将 flex-grow
设置为 1 似乎可以实现您想要的效果。
const canvas = document.getElementById("canvas");
function paint() {
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
const ctx = canvas.getContext("2d");
ctx.fillText(canvas.height, canvas.width / 2, canvas.height / 2);
}
paint();
new ResizeObserver(paint).observe(canvas);
.main {
display: flex;
flex-direction: column;
height: 100%;
}
canvas {
height: 0;
flex-grow: 1;
}
html, body {
height: 100%;
margin: 0;
}
<div class="main">
<div class="header">
Header
</div>
<canvas id="canvas" class="canvas"></canvas>
<div class="footer">
Footer
</div>
</div>
以下示例创建页眉、canvas 和页脚。 canvas 被告知填充页眉和页脚之间的 space。发生以下情况:
- 扩大window:canvas增长
- 缩小window:出现滚动条,但我希望canvas缩小
为什么 canvas 没有收缩,我怎样才能让它收缩?
const canvas = document.getElementById("canvas");
function paint() {
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
const ctx = canvas.getContext("2d");
ctx.fillText(canvas.height, canvas.width / 2, canvas.height / 2);
}
paint();
new ResizeObserver(paint).observe(canvas);
.main {
height: 100%;
display: flex;
flex-flow: column;
}
.canvas {
flex: 1 0 0%;
}
html, body {
height: 100%;
margin: 0;
}
<div class="main">
<div class="header">
Header
</div>
<canvas id="canvas" class="canvas"></canvas>
<div class="footer">
Footer
</div>
</div>
将 canvas
高度设置为 0 并将 flex-grow
设置为 1 似乎可以实现您想要的效果。
const canvas = document.getElementById("canvas");
function paint() {
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
const ctx = canvas.getContext("2d");
ctx.fillText(canvas.height, canvas.width / 2, canvas.height / 2);
}
paint();
new ResizeObserver(paint).observe(canvas);
.main {
display: flex;
flex-direction: column;
height: 100%;
}
canvas {
height: 0;
flex-grow: 1;
}
html, body {
height: 100%;
margin: 0;
}
<div class="main">
<div class="header">
Header
</div>
<canvas id="canvas" class="canvas"></canvas>
<div class="footer">
Footer
</div>
</div>