我希望打开从 Sketchfab 下载的 3D 图像,并使用三个 js 使其具有交互性和可点击性。我已按照 ChatGPT 的说明进行操作,因此文件夹中包含我需要的所有 scrypt(GLTFLoader.js、main.js、OrbitControls.js、 Three.module.js、index.html 和图像本身(gltf 格式)我正在使用 Visual Studio Code 的本地服务器,开发人员工具中没有出现错误消息,但是网站是空白的,我看不到图像。
我尝试过 python -m https.server -> 相同的空白屏幕 我尝试过 gltf 和 glb 格式的不同图像 另外,ChatGPT 建议我使用简单的几何结构,例如立方体,但它仍然不起作用
import * as THREE from './three.module.js';
import { GLTFLoader } from './GLTFLoader.js';
import { OrbitControls } from './OrbitControls.js';
// Initialize scene, camera, and renderer
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);
// Add lighting
const ambientLight = new THREE.AmbientLight(0x404040);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
scene.add(directionalLight);
// Load the brain model
const loader = new GLTFLoader();
loader.load('models/brain_model.gltf', (gltf) => {
const brain = gltf.scene;
scene.add(brain);
brain.rotation.y = Math.PI; // Initial rotation
}, undefined, (error) => {
console.error('An error happened while loading the model:', error);
});
// Set camera position
camera.position.z = 5;
// Add orbit controls
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.25;
controls.enableZoom = true;
// Animation loop
function animate() {
requestAnimationFrame(animate);
controls.update();
renderer.render(scene, camera);
}
animate();
// Handle window resize
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
html 文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>3D Interactive Brain</title>
<style>
body { margin: 0; overflow: hidden; }
canvas { display: block; }
</style>
</head>
<body>
<script type= "/module" src="/main.js"></script>
</body>
</html>
目录结构
threejs-brain-project/
├── index.html
├── main.js
├── three.module.js
├── GLTFLoader.js
├── OrbitControls.js
└── models/
└── brain_model.glb
尝试这样:
<script type="module" src="main.js"></script>
和进口
import * as THREE from './three.module.js';
import { GLTFLoader } from './GLTFLoader.js';
import { OrbitControls } from './OrbitControls.js';