Three.js 粒子效果

前言

最近項目用到了粒子效果,效果預覽以下:html

完整項目預覽:git

解決思路

提取模型中頂點信息,而後藉助 three.js 的 Points 實現。github

提取頂點信息

如何提取 obj 模型的頂點信息,點此查看typescript

關鍵代碼

three.js 初始化json

// 場景
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);
複製代碼

點材質初始化canvas

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
});
複製代碼

獲取模型中的頂點信息並賦值頂點信息api

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);
複製代碼

開始渲染markdown

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

總結

three.js 爲實現粒子效果提供了完整的接口,咱們只須要獲取並賦值頂點信息就能夠了。oop

更多文章

相關文章
相關標籤/搜索