three.js 实现波纹效果
时间: 2023-11-04 16:05:47 浏览: 21
要实现波纹效果,可以使用Three.js中的ShaderMaterial和RenderTarget,以下是实现波纹效果的代码:
```
// 创建渲染器
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// 创建相机和场景
const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.z = 5;
const scene = new THREE.Scene();
// 创建平面和波纹材质
const geometry = new THREE.PlaneGeometry(10, 10, 256, 256);
const material = new THREE.ShaderMaterial({
uniforms: {
time: { value: 0 },
waveLength: { value: 1.0 },
amplitude: { value: 0.1 }
},
vertexShader: `
uniform float time;
uniform float waveLength;
uniform float amplitude;
void main() {
vec3 pos = position;
pos.y += sin(pos.x * waveLength + time) * amplitude;
pos.y += sin(pos.y * waveLength + time) * amplitude;
gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);
}
`,
fragmentShader: `
void main() {
gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
}
`
});
const plane = new THREE.Mesh(geometry, material);
scene.add(plane);
// 创建一个RenderTarget
const renderTarget = new THREE.WebGLRenderTarget(window.innerWidth, window.innerHeight);
// 渲染函数
function render() {
requestAnimationFrame(render);
// 更新波纹材质的uniforms
material.uniforms.time.value += 0.1;
// 渲染到RenderTarget
renderer.setRenderTarget(renderTarget);
renderer.render(scene, camera);
// 渲染到屏幕
renderer.setRenderTarget(null);
material.map = renderTarget.texture;
renderer.render(scene, camera);
}
render();
```
其中,ShaderMaterial的vertexShader实现了波纹的效果,fragmentShader是一个空的片元着色器,可以根据需要进行修改。uniforms中的time控制波纹的时间,waveLength和amplitude分别控制波长和振幅的大小。RenderTarget用于将渲染结果渲染到纹理上,然后再将纹理渲染到屏幕上,这样就可以实现波纹效果。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)