我已经为我的问题准备了a simple test web page at Github(使用main.css文件):
在垂直flexbox布局中,我try 使用ResizeObserver来查看具有flex-grow:1的父dis元素,然后在其子canvas元素上保持1:1的长宽比.
我试图保持canvas长宽比的原因是in my real app a PixiJS canvas is embedded in a ReactJS app,如果我只是zoom canvas元素以填充dis父级,那么PixiJS内容就会被拉伸:
不幸的是,parent
迪夫元素将hint
迪夫元素从屏幕底部推出-
我认为,我的代码中缺少一些小东西,请推荐一个修复方法:
const parentElement = document.getElementById("parent");
const childElement = document.getElementById("child");
const resizeObserver = new ResizeObserver((entries) => {
for (let entry of entries) {
const { width, height } = entry.contentRect;
const minDimension = Math.min(width, height);
console.log(
`parent: ${width} x ${height} -> child: ${minDimension} x ${minDimension}`
);
childElement.style.width = `${minDimension}px`;
childElement.style.height = `${minDimension}px`;
}
});
resizeObserver.observe(parentElement);
html,
body {
margin: 0;
padding: 0;
overflow: hidden;
}
.flexRoot {
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: stretch;
width: 100%;
height: 100vh;
}
/* the parent holds: status, canvas, hint */
.parent {
border: 4px solid red;
flex-grow: 1;
}
canvas {
width: 1020px;
height: 1020px;
background-color: yellow;
border: 4px green dotted;
box-sizing: border-box;
}
.hint,
.status {
background: lightblue;
font-style: italic;
text-align: center;
flex-grow: 0;
}
<div class="flexRoot">
<div class="status">Game #1 Score1:Score2</div>
<div class="parent" id="parent">
<canvas id="child"></canvas>
</div>
<div class="hint">A game hint to do this and that...</div>
</div>