用threejs编写一段动态水波纹模型,要求动态好看
时间: 2024-05-30 15:14:24 浏览: 120
以下是一个简单的threejs动态水波纹模型代码:
```javascript
// 初始化场景、相机和渲染器
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// 创建一个平面几何体作为水面
var geometry = new THREE.PlaneGeometry(10, 10, 64, 64);
var material = new THREE.MeshStandardMaterial({ color: 0x0066ff });
var plane = new THREE.Mesh(geometry, material);
scene.add(plane);
// 创建一个着色器材质作为水波纹效果
var waterMaterial = new THREE.ShaderMaterial({
uniforms: {
time: { value: 0 },
resolution: { value: new THREE.Vector2() },
},
vertexShader: document.getElementById('vertexShader').textContent,
fragmentShader: document.getElementById('fragmentShader').textContent,
});
// 替换平面的材质为水波纹效果材质
plane.material = waterMaterial;
// 设置相机位置
camera.position.z = 5;
// 渲染循环
var animate = function () {
requestAnimationFrame(animate);
// 更新水波纹效果的时间和分辨率
waterMaterial.uniforms.time.value += 0.01;
waterMaterial.uniforms.resolution.value.x = window.innerWidth;
waterMaterial.uniforms.resolution.value.y = window.innerHeight;
renderer.render(scene, camera);
};
animate();
```
着色器代码如下:
```glsl
// 顶点着色器
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
// 片元着色器
uniform vec2 resolution;
uniform float time;
varying vec2 vUv;
void main() {
vec2 position = -1.0 + 2.0 * vUv;
float freq = 2.0;
float amp = 0.1;
float speed = 1.0;
float noise = sin(position.x * freq + time * speed) * amp;
vec3 color = vec3(0.0, 0.0, 1.0);
gl_FragColor = vec4(color * noise, 1.0);
}
```
效果如下:
![动态水波纹效果](https://i.imgur.com/iP7FJ8A.gif)
阅读全文