Three.js导入WebGL时输出白屏

问题描述 投票:0回答:0

我正在为大学开展一个项目,该项目使用

three.js
库。我对与计算机图形学相关的一切都是陌生的,并且已经开始专门为我的课程学习这个。

我认为遵循他们自己的教程(创建场景)可能有助于建立我自己对

three.js
WebGL
实际做的事情的看法。

根据上面链接中提到的代码,我成功地创建了一个带有自身旋转的绿色立方体的场景。

基本上,我有一个

index.html
文件,它有一个
<script>
标签指向我的
main.js
文件,看起来像这样:

import * as THREE from 'three';


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(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({color: 0x00ff00});
const cube     = new THREE.Mesh(geometry, material);
scene.add(cube);

camera.position.z = 5;

function animate() {
    requestAnimationFrame(animate);
    
    cube.rotation.x += 0.01;
    cube.rotation.y += 0.01;
    
    renderer.render(scene, camera);
}

// Initiate function or other initializations here
animate();

我正在使用 vite 来启动我的静态服务器。这是我的输出:

问题出现在本教程的下一节,与 WebGL 兼容性检查 相关的部分。附加的链接会将您重定向到一个教程部分,其中包含一段包含支票的代码。

在调用

main.js
函数之前,我尝试用一个导入(
WebGL
)和检查更新我的
animate()

import * as THREE from 'three';

// First Change: importing WebGL
import { WebGL } from 'three/addons/capabilities/WebGL.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(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({color: 0x00ff00});
const cube     = new THREE.Mesh(geometry, material);
scene.add(cube);

camera.position.z = 5;

function animate() {
    requestAnimationFrame(animate);
    
    cube.rotation.x += 0.01;
    cube.rotation.y += 0.01;
    
    renderer.render(scene, camera);
}

// Here comes the second change: if statement before calling animate()
if ( WebGL.isWebGLAvailable() ) {
    animate();
} else {
    const warning = WebGL.getWebGLErrorMessage();
    document.getElementById( 'container' ).appendChild( warning );
}

问题是,我现在收到一个白屏。导航到 http://localhost:5173/ 不再输出我旋转的绿色立方体。我已经意识到删除

if
语句并不能解决任何问题,问题在于
import
WebGL
语句。删除
import
时,画布似乎又可以正常输出了。

请理解我对 JavaScript 和 3D 渲染是什么意思仍然是新手,但我愿意学习。

我的问题是,实际导致白屏的问题可能是什么?

javascript three.js webgl
© www.soinside.com 2019 - 2024. All rights reserved.