我正在使用 Three.js 渲染到画布。我想要一个
div
位于画布上方,另一个位于画布下方。画布应该填充两者之间的剩余空间(即使这意味着只要视口大小发生变化,画布就会改变纵横比,也没关系)。这 3 个元素一起应始终填充 100% 的视口,但不能超过它并导致出现滚动条。
如果不清楚,这是我制作的 gif(使用静态图像而不是画布)准确地演示了我想要实现的目标:
我认为这将是一个简单的弹性盒布局,但我似乎无法让它工作。要么出现滚动条,要么底部元素被推到视口之外。这是我的尝试之一(单击“运行代码片段”>“完整页面”):
const canvas = document.querySelector('canvas');
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera();
camera.position.z = 5;
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({ color: '#ff0000' });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
requestAnimationFrame(render);
function render() {
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
if (resizeRendererToDisplaySize(renderer)) {
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
}
renderer.render(scene, camera);
requestAnimationFrame(render);
}
function resizeRendererToDisplaySize(renderer) {
const width = canvas.clientWidth;
const height = canvas.clientHeight;
const needResize = canvas.width !== width || canvas.height !== height;
if (needResize) {
renderer.setSize(width, height, false);
}
return needResize;
}
html, body {
height: 100%;
margin: 0;
}
.container {
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
}
.top, .bottom {
padding: 10px;
}
.middle {
flex: 1;
}
.middle canvas {
width: 100%;
height: 100%;
display: block;
}
<div class="container">
<div class="top">Top</div>
<div class="middle">
<canvas></canvas>
</div>
<div class="bottom">Bottom</div>
</div>
<script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/[email protected]/build/three.module.js",
"three/addons/": "https://unpkg.com/[email protected]/examples/jsm/"
}
}
</script>
<script type="module">
import * as THREE from 'three';
window.THREE = THREE;
</script>
奇怪的是,如果你将
flex-direction
更改为 row
,你会发现它完全按照我想要的方式工作,但是是水平的。我只是希望它能够垂直工作。可以吗?