我是 Javascript 和 ThreeJS 的新手。我有一個出現在靜態背景之上的 3D 旋轉立方體,但一個令人沮喪的特性是立方體通常首先出現,然后出現背景影像。如何確保首先渲染背景?具體來說,我總是希望背景影像出現在立方體之前。
我的代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My first three.js app</title>
<style>
body { margin: 0; }
</style>
</head>
<body>
<script src="js/three.js"></script>
<script>
function resize() {
var aspect = window.innerWidth / window.innerHeight;
let texAspect = bgWidth / bgHeight;
let relAspect = aspect / texAspect;
bgTexture.repeat = new THREE.Vector2( Math.max(relAspect, 1), Math.max(1/relAspect,1) );
bgTexture.offset = new THREE.Vector2( -Math.max(relAspect-1, 0)/2, -Math.max(1/relAspect-1, 0)/2 );
renderer.setSize(window.innerWidth, window.innerHeight);
camera.aspect = aspect;
camera.updateProjectionMatrix();
}
const scene = new THREE.Scene();
// Arguments:
// 1) Field of Value (degrees)
// 2) Aspect ratio
// 3) Near clipping plane
// 4) Far clipping plane
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
const renderer = new THREE.WebGLRenderer();
// Need to set size of renderer. For performance, may want to reduce size.
// Can also reduce resolution by passing false as third arg to .setSize
renderer.setSize( window.innerWidth, window.innerHeight );
// Add the rendered to the HTML
document.body.appendChild( renderer.domElement );
// A BoxGeometry is an object that contains all points (vertices) and fill (faces)
// of the cube
const geometry = new THREE.BoxGeometry();
// Determines surface color (maybe texture?)
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
// Mesh takes a geometry and applies the material to it
const cube = new THREE.Mesh( geometry, material );
// Add background image
const loader = new THREE.TextureLoader();
bgTexture = loader.load('https://images.pexels.com/photos/1205301/pexels-photo-1205301.jpeg' ,
function(texture) {
// Resize image to fit in window
// Code from https://stackoverflow.com/a/48126806/4570472
var img = texture.image;
var bgWidth = img.width;
var bgHeight = img.height;
resize();
});
scene.background = bgTexture;
// By default, whatever we add to the scene will be at coordinates (0, 0, 0)
scene.add( cube );
camera.position.z = 5;
// This somehow creates a loop that causes the rendered to draw the scene
// every time the screen is refreshed (typically 60fps)
function animate() {
requestAnimationFrame( animate );
cube.rotation.x = 0.01;
cube.rotation.y = 0.01;
renderer.render( scene, camera );
}
animate();
</script>
</body>
</html>
uj5u.com熱心網友回復:
發生這種情況是因為加載紋理所需的時間比 Three.js 設定場景其余部分所需的時間要長。您已經有一個onLoad回呼的處理程式TextureLoader.load(),因此我們可以使用它來調整行為。
在 之前scene.add( cube );,添加一個新行:
cube.visible = false;
現在立方體仍將添加到場景中,但它不可見。現在在結束的resize()呼叫之后function(texture),添加
cube.visible = true;
在本地測驗問題和解決方案時,我遇到了其他一些不太重要的代碼問題。您可以在此 Gist中看到我必須進行的所有更改才能使其正常運行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/421450.html
標籤:
