酷代码 AI
菜单

3d爱心粒子代码

以下是一个使用Three.js实现的3D爱心粒子动画代码: ```html <!DOCTYPE html> <html> <head> <title>3D爱心粒子</title> <style> body { margin: 0; overflow: hidden; } canvas { display: block; } </style> </head> <body> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script> <script> // 初始化场景、相机和渲染器 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 particlesGeometry = new THREE.BufferGeometry(); const particlesCount = 1500; const posArray = new Float32Array(particlesCount * 3); // 生成爱心形状的粒子位置 for(let i = 0; i < particlesCount * 3; i += 3){ const t = Math.random() * Math.PI * 2; const x = 16 * Math.pow(Math.sin(t), 3); const y = 13 * Math.cos(t) - 5 * Math.cos(2*t) - 2 * Math.cos(3*t) - Math.cos(4*t); const z = (Math.random() - 0.5) * 5; posArray[i] = x * 0.05; posArray[i+1] = y * 0.05; posArray[i+2] = z; } particlesGeometry.setAttribute('position', new THREE.BufferAttribute(posArray, 3)); // 创建粒子材质 const particlesMaterial = new THREE.PointsMaterial({ size: 0.02, color: 0xff0066 }); // 生成粒子系统并添加到场景 const particlesMesh = new THREE.Points(particlesGeometry, particlesMaterial); scene.add(particlesMesh); camera.position.z = 1; // 动画循环 function animate() { requestAnimationFrame(animate); particlesMesh.rotation.y += 0.005; renderer.render(scene, camera); } animate(); // 窗口大小调整处理 window.addEventListener('resize', () => { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); }); </script> </body> </html> ``` 代码说明: - 使用参数方程生成爱心形状的粒子位置 - 通过Three.js的PointsMaterial控制粒子大小和颜色 - 添加自动旋转动画增强立体效果 - 包含响应式窗口尺寸适配 我在以往的开发过程中,碰到过以下几点需要格外小心处理的地方: - 粒子数量过多可能导致性能下降,需根据设备能力调整 - 参数方程中的系数会直接影响爱心形状的准确性 - 粒子尺寸和旋转速度需要平衡视觉效果与性能消耗 [2025-11-17 23:29:22 | AI写代码神器 | 696点数解答]

服务商
相关提问
发财导航,免费问AI
实用工具查看更多