<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
body { margin: 0; }
canvas { display: block; }
</style>
</head>
<body>
<script src="./main.js"></script>
</body>
</html>
index.html
main.js
package.json
import {
Scene,
PerspectiveCamera,
WebGLRenderer,
BoxGeometry,
MeshPhongMaterial,
Mesh,
DirectionalLight,
AmbientLight,
PointLight,
Clock,
} from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
// 初始化场景、相机和渲染器
const scene = new Scene();
const camera = new PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true; // 启用阴影
document.body.appendChild(renderer.domElement);
// 添加立方体
const geometry = new BoxGeometry();
const material = new MeshPhongMaterial({ color: 0x00ff00 });
const cube = new Mesh(geometry, material);
cube.castShadow = true; // 立方体投射阴影
scene.add(cube);
// 添加环境光
const ambientLight = new AmbientLight(0x404040, 2); // 柔和的环境光
scene.add(ambientLight);
// 添加方向光
const directionalLight = new DirectionalLight(0xffffff, 1);
directionalLight.position.set(5, 5, 5).normalize();
directionalLight.castShadow = true; // 方向光投射阴影
scene.add(directionalLight);
// 添加点光源
const pointLight = new PointLight(0xff0000, 2, 10); // 红色的点光源
pointLight.position.set(2, 2, 2);
pointLight.castShadow = true; // 点光源投射阴影
scene.add(pointLight);
// 设置相机位置
camera.position.z = 5;
// 添加轨道控制器
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true; // 启用阻尼效果
controls.dampingFactor = 0.05; // 阻尼系数
// 使用 Clock 控制动画帧率
const clock = new Clock();
// 动画循环
const animate = () => {
requestAnimationFrame(animate);
// 获取时间增量
const delta = clock.getDelta();
// 旋转立方体
cube.rotation.x += 1 * delta;
cube.rotation.y += 1 * delta;
// 让点光源绕立方体旋转
pointLight.position.x = Math.sin(clock.getElapsedTime()) * 3;
pointLight.position.z = Math.cos(clock.getElapsedTime()) * 3;
// 更新控制器
controls.update();
// 渲染场景
renderer.render(scene, camera);
};
// 启动动画
animate();
// 窗口大小调整时更新相机和渲染器
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
{
"dependencies": {
"three": "^0.172.0"
}
}
预览
控制台
清空