maath + three.js 实现粒子动效

61 阅读1分钟

screenshot-20250808-174725.png

maath介绍

Maath——你的3D编程得力助手,集合了各种数学小工具的库,它的目标是让你在进行3D编程时能更专注于创意而非基础计算。通过一系列精心设计的函数,Maath可以帮助你快速生成点集、处理缓冲区数据,甚至创建平滑的动画效果。

官网:maath.pmnd.rs

安装:

yarn add maath

代码片段

  <template>
	<canvas ref="canvas" />
  </template>
  
  <script>
  import { ref, onMounted, onUnmounted } from 'vue';
  import * as THREE from 'three';
  import { inSphere } from 'maath/random';
  import { damp3 } from 'maath/easing';
  
  export default {
	setup() {
	  const canvas = ref(null);
	  let scene, camera, renderer, points;
  
	  // 初始化场景
	  const init = () => {
		scene = new THREE.Scene();
		camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
		renderer = new THREE.WebGLRenderer({ canvas: canvas.value });
	
		// 使用 maath 生成点
		const positions = inSphere(new Float32Array(10000 * 3), { radius: 20 });
		const geometry = new THREE.BufferGeometry();
		geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
		const material = new THREE.PointsMaterial({ size: 0.1, color: 0x0000ff });
		points = new THREE.Points(geometry, material);
		scene.add(points);
	  };
  
	  // 动画循环
	  let frameId;
	  const animate = () => {
		// 使用 maath 的阻尼函数
		damp3(points.rotation, [0, Date.now() * 0.0001, 0], 0.25, 8);
		renderer.render(scene, camera);
		frameId = requestAnimationFrame(animate);
	  };
  
	  onMounted(() => {
		init();
		animate();
	  });
  
	  onUnmounted(() => {
		cancelAnimationFrame(frameId);
		renderer.dispose();
	  });
  
	  return { canvas };
	}
  };
  </script>