用three.js实现水面倒影
时间: 2023-11-12 13:47:04 浏览: 218
要使用Three.js实现水面倒影效果,您可以按照以下步骤进行:
1. 首先,确保已经引入了Three.js库。您可以使用以下代码来引入最新版本的Three.js库:
```html
<script src="https://cdn.jsdelivr.net/npm/three@latest"></script>
```
2. 创建一个场景、相机和渲染器:
```javascript
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);
```
3. 创建一个平面作为水面,并设置其材质为`THREE.MeshBasicMaterial`:
```javascript
const waterGeometry = new THREE.PlaneGeometry(100, 100);
const waterMaterial = new THREE.MeshBasicMaterial({ color: 0x0000ff });
const water = new THREE.Mesh(waterGeometry, waterMaterial);
scene.add(water);
```
4. 创建一个镜像相机,并将其位置设置在水面下方:
```javascript
const mirrorCamera = new THREE.CubeCamera(0.1, 1000, 512);
scene.add(mirrorCamera);
mirrorCamera.position.y = -1; // 设置水面下方的位置
mirrorCamera.updateCubeMap(renderer, scene);
```
5. 创建一个地面平面,并将其材质设置为具有倒影效果的`THREE.MeshBasicMaterial`,使用水面的镜像贴图:
```javascript
const groundGeometry = new THREE.PlaneGeometry(100, 100);
const groundMaterial = new THREE.MeshBasicMaterial({ envMap: mirrorCamera.renderTarget });
const ground = new THREE.Mesh(groundGeometry, groundMaterial);
scene.add(ground);
```
6. 在渲染循环中,更新水面和镜像相机:
```javascript
function animate() {
requestAnimationFrame(animate);
water.rotation.x += 0.01; // 可选:使水面旋转
mirrorCamera.position.copy(water.position); // 将镜像相机位置设置为水面位置的副本
mirrorCamera.lookAt(scene.position); // 将镜像相机对准场景中心
mirrorCamera.updateCubeMap(renderer, scene); // 更新镜像相机的立方体贴图
renderer.render(scene, camera);
}
animate();
```
通过以上步骤,您应该能够在Three.js中实现水面倒影效果。您可以根据需要调整材质、几何形状和动画效果来实现您想要的效果。
阅读全文