Three.js 粒子效果

4,844 阅读1分钟

前言

最近项目用到了粒子效果,效果预览如下:

完整项目预览:

解决思路

提取模型中顶点信息,然后借助 three.js 的 Points 实现。

提取顶点信息

如何提取 obj 模型的顶点信息,点此查看

关键代码

three.js 初始化

// 场景
this.scene = new THREE.Scene();
// 渲染器
this.renderer = new THREE.WebGLRenderer({canvas:this.canvas,antialias: true, alpha:true});
this.renderer.setSize(window.innerWidth,window.innerHeight,false);
this.renderer.setViewport(0,0,window.innerWidth,window.innerHeight);
// 相机
this.camera = new THREE.PerspectiveCamera(45,window.innerWidth/window.innerHeight,1,4000);
this.camera.position.set(0,0,200);
this.scene.add(this.camera);

点材质初始化

this.particleMaterial = new THREE.PointsMaterial({
    size: 1.5,
    color: 0x6976a3,
    map: new THREE.TextureLoader().load(textureAssets), // 贴图
    blending: THREE.AdditiveBlending,
    depthTest: !0,
    alphaTest: .1,
    opacity: 1,
    transparent: !0
});

获取模型中的顶点信息并赋值顶点信息

this.geo = new THREE.Geometry(); // 创建一个 Geometry 来存储顶点信息
this.geo.center();
this.geo.normalize();
const vertices = json.vertices; // json 是从 obj 模型导出的数据,这里获取顶点信息
for(let i = 0; i < vertices.length/3; i++){
    const particle:THREE.Vector3 = new THREE.Vector3(
        vertices[i*3],
        vertices[i*3+1],
        vertices[i*3+2],
    );
    this.geo.vertices.push(particle);
}
this.points = new THREE.Points(this.geo,this.particleMaterial); // 创建粒子
this.scene.add(this.points);

开始渲染

private render(){
    this.animationFrame = requestAnimationFrame(()=>{
        this.render();
    });
    this.geo.verticesNeedUpdate = true;
    this.renderer.render(this.scene,this.camera);
}
this.render();

总结

three.js 为实现粒子效果提供了完整的接口,我们只需要获取并赋值顶点信息就可以了。

更多文章