酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

3D粒子爱心动态

要实现 3D 粒子爱心动态效果,可以使用 Three.js 这个 JavaScript 3D 库。以下是一个简单的示例代码: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>3D Particle Heart</title> <!-- 引入 Three.js 库 --> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script> </head> <body> <script> // 创建场景 const scene = new THREE.Scene(); // 创建相机,设置视角 const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); camera.position.z = 5; // 创建渲染器 const renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); // 定义爱心函数 function heartFunction(t) { 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 = 0; return new THREE.Vector3(x, y, z); } // 创建粒子系统 const particlesGeometry = new THREE.BufferGeometry(); const particleCount = 1000; const positions = new Float32Array(particleCount * 3); for (let i = 0; i < particleCount; i++) { const t = Math.random() * Math.PI * 2; const heartPoint = heartFunction(t); const index = i * 3; positions[index] = heartPoint.x; positions[index + 1] = heartPoint.y; positions[index + 2] = heartPoint.z; } particlesGeometry.setAttribute('position', new THREE.BufferAttribute(positions, 3)); const particlesMaterial = new THREE.PointsMaterial({ color: 0xff0000, size: 0.1 }); const particles = new THREE.Points(particlesGeometry, particlesMaterial); scene.add(particles); // 动画循环 function animate() { requestAnimationFrame(animate); // 更新粒子位置 const positions = particlesGeometry.attributes.position.array; for (let i = 0; i < particleCount; i++) { const index = i * 3; const t = Math.random() * Math.PI * 2; const heartPoint = heartFunction(t); positions[index] = heartPoint.x; positions[index + 1] = heartPoint.y; positions[index + 2] = heartPoint.z; } particlesGeometry.attributes.position.needsUpdate = true; 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> ``` 代码解释 1. 创建场景、相机和渲染器:使用 Three.js 的基本组件来搭建 3D 环境。 2. 定义爱心函数:通过数学公式定义爱心的形状。 3. 创建粒子系统:生成大量粒子,并将它们的位置设置在爱心形状上。 4. 动画循环:在每一帧中更新粒子的位置,实现动态效果。 额外注意逻辑点 1. 粒子数量的调整会影响性能和效果,过多的粒子可能会导致性能下降。 2. 可以通过修改 `PointsMaterial` 的 `size` 属性来改变粒子的大小。 3. 在更新粒子位置时,要确保 `particlesGeometry.attributes.position.needsUpdate` 设置为 `true`,以通知 Three.js 更新粒子的位置。 [2025-06-12 23:05:24 | AI写代码神器 | 977点数解答]

相关提问