文档
Three.js Hello World — 旋转立方体
目标
创建一个带光照和旋转动画的 3D 立方体场景,这是 Three.js 最经典的入门示例。
完整代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>Three.js 旋转立方体</title>
<style>
body { margin: 0; overflow: hidden; background: #000; }
canvas { display: block; }
</style>
</head>
<body>
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three@0.160.0/build/three.module.js"
}
}
</script>
<script type="module">
import * as THREE from 'three';
// ========== 1. 创建场景 ==========
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x1a1a2e);
// ========== 2. 创建相机 ==========
const camera = new THREE.PerspectiveCamera(
75, // 视野角度
window.innerWidth / window.innerHeight, // 宽高比
0.1, // 近裁面
1000 // 远裁面
);
camera.position.z = 5;
// ========== 3. 创建渲染器 ==========
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(window.devicePixelRatio);
document.body.appendChild(renderer.domElement);
// ========== 4. 创建立方体 ==========
const geometry = new THREE.BoxGeometry(1.5, 1.5, 1.5);
const material = new THREE.MeshStandardMaterial({
color: 0x00ff88,
roughness: 0.3,
metalness: 0.1,
});
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
// ========== 5. 添加光源 ==========
// 环境光(基础亮度)
const ambientLight = new THREE.AmbientLight(0x404040, 0.5);
scene.add(ambientLight);
// 方向光(产生阴影和立体感)
const directionalLight = new THREE.DirectionalLight(0xffffff, 1.2);
directionalLight.position.set(5, 5, 5);
scene.add(directionalLight);
// ========== 6. 动画循环 ==========
function animate() {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.015;
renderer.render(scene, camera);
}
animate();
// ========== 7. 窗口自适应 ==========
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
</script>
</body>
</html>
运行步骤
- 将上述代码保存为
index.html - 用浏览器直接打开(需通过 localhost 运行,或直接用 Live Server)
- 你将看到一个带光照的绿色立方体持续旋转
预期输出
- 深色背景上显示一个绿色立方体
- 立方体沿 X 和 Y 轴持续旋转
- 有明暗面变化(光照效果)
- 调整窗口大小时场景自适应