threejs 阴影例子
时间: 2024-07-03 13:00:24 浏览: 80
Three.js 是一个基于 JavaScript 的 3D 渲染库,用于在浏览器中创建交互式的 3D 场景。它提供了一系列功能,包括光照、阴影效果,以便让你的 3D 物体看起来更真实。其中一个常见的例子就是阴影技术,比如投射阴影(Projected Shadows)和逐像素阴影(Pixelated Shadows)。
一个简单的 Three.js 投射阴影的例子通常会涉及以下步骤:
1. 创建光源(Light):使用 `THREE.PointLight` 或 `THREE.DirectionalLight` 创建光源,并将其位置设置为光源发出的方向。
2. 创建材质(Material):使用支持阴影的材质,如 `THREE.MeshBasicMaterial` 或 `THREE.MeshStandardMaterial`,并设置其接收阴影属性为 `true`。
3. 创建场景(Scene)、相机(Camera)和渲染器(Renderer):设置阴影映射参数。
4. 更新场景和渲染:在每帧更新中,确保相机和光源的位置被正确更新。
以下是一个简化的代码片段,展示了如何创建一个具有投射阴影的立方体:
```javascript
// 初始化场景、相机和渲染器
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5; // 设置相机距离
const renderer = new THREE.WebGLRenderer();
renderer.shadowMap.enabled = true;
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// 创建光源
const light = new THREE.PointLight(0xffffff, 1, 100);
light.castShadow = true;
light.position.set(10, 10, 10); // 设置光源位置
// 创建立方体
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshStandardMaterial({ color: 0x00ff00, receivingShadows: true });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
// 设置阴影映射参数
camera.position.applyMatrix4(light.shadow.matrixWorldInverse);
light.shadow.camera.near = 0.1;
light.shadow.camera.far = 100;
// 渲染
function animate() {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
```
阅读全文
相关推荐


















