【发布时间】:2022-01-01 12:01:28
【问题描述】:
我正在尝试让我的 three.js 场景显示在一些卡片上方和导航栏下方。现在我的场景在卡片下面渲染,没有居中。在搜索其他相关论坛帖子后,我似乎无法弄清楚我做错了什么。
HTML:
<script src="../static/javascript/three.js"></script>
<script src="../static/javascript/explore3D.js"></script>
<div class="container">
<div class = "row">
<div id="canvas"></div>
</div>
</div>
<div class="py-5 bg-light">
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="card mb-6 shadow-sm">
<div class="card-body">
</div>
</div>
</div>
<div class="col-md-6">
<div class="card mb-6 shadow-sm">
<div class="card-body">
</div>
</div>
</div>
</div>
</div>
</div>
CSS:
#canvas {
position: fixed;
outline: none;
}
JS:
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
const renderer = new THREE.WebGLRenderer();
renderer.setSize( 700, 400 );
document.querySelector('#canvas').appendChild( renderer.domElement );
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
const cube = new THREE.Mesh( geometry, material );
scene.add( cube );
camera.position.z = 5;
const animate = function () {
requestAnimationFrame( animate );
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render( scene, camera );
};
animate();
非常感谢任何人的帮助!如果需要更多上下文来提供答案,请告诉我。
编辑:我将document.body.appendChild( renderer.domElement ); 切换为document.querySelector('#canvas').appendChild( renderer.domElement ); 此更改现在在控制台中引发TypeError: null is not an object 异常,并且没有呈现任何内容。
编辑:我也尝试过document.getElementById('canvas').appendChild( renderer.domElement );,但这也会导致在控制台中抛出相同的异常。
编辑:我刚刚引用了这篇文章:Get Element By Id Not working 是否有可能因为我在呈现页面之前调用了这个函数,所以我正在寻找的元素不存在?
【问题讨论】:
标签: javascript html css three.js rendering