使用threejs 实现粒子动画的代码
时间: 2023-01-30 08:20:34 浏览: 97
三维粒子动画可以使用 `THREE.Points` 和 `THREE.PointCloud` 来实现。
首先,你需要准备粒子的纹理贴图和顶点数据。
然后,你可以这样创建一个粒子系统:
```
const particles = new THREE.Points(geometry, material);
scene.add(particles);
```
其中,`geometry` 是粒子的顶点几何体,`material` 是粒子的材质。
你还可以使用动画循环更新粒子的位置,例如:
```
function animate() {
particles.rotation.x += 0.01;
particles.rotation.y += 0.02;
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
```
完整的示例代码如下:
```
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);
const texture = new THREE.TextureLoader().load('particle.png');
const material = new THREE.PointsMaterial({
size: 0.1,
transparent: true,
depthWrite: false,
map: texture
});
const geometry = new THREE.BufferGeometry();
const vertices = [];
for (let i = 0; i < 10000; i++) {
vertices.push(THREE.Math.randFloatSpread(50));
vertices.push(THREE.Math.randFloatSpread(50));
vertices.push(THREE.Math.randFloatSpread(50));
}
geometry.addAttribute('position', new THREE.Float32BufferAttribute(vertices, 3));
const particles = new THREE.Points(geometry, material);
scene.add(particles);
camera.position.z = 100;
function animate() {
particles.rotation.x += 0.01;
particles.rotation.y += 0.02;
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
animate();
```
希望这能帮到你!