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

用HTML做一个动态粒子爱心代码

# HTML动态粒子爱心代码 以下是一个使用HTML、CSS和JavaScript创建的动态粒子爱心效果: ```html <!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>动态粒子爱心</title> <style> body { margin: 0; overflow: hidden; background-color: #000; } canvas { display: block; } </style> </head> <body> <canvas id="heartCanvas"></canvas> <script> const canvas = document.getElementById('heartCanvas'); const ctx = canvas.getContext('2d'); // 设置画布大小为窗口大小 canvas.width = window.innerWidth; canvas.height = window.innerHeight; // 粒子数组 const particles = []; const particleCount = 150; // 粒子类 class Particle { constructor() { this.x = Math.random() * canvas.width; this.y = Math.random() * canvas.height; this.size = Math.random() * 3 + 1; this.speedX = Math.random() * 2 - 1; this.speedY = Math.random() * 2 - 1; this.color = `hsl(${Math.random() * 60 + 330}, 100%, 50%)`; } update() { // 爱心形状的引力 const dx = this.x - canvas.width / 2; const dy = this.y - canvas.height / 2; const distance = Math.sqrt(dx * dx + dy * dy); // 爱心方程: (x² + y² - 1)³ - x²y³ = 0 const heartX = dx / 50; const heartY = -dy / 50; const heartEq = Math.pow((heartX * heartX + heartY * heartY - 1), 3) - heartX * heartX * heartY * heartY * heartY; if (heartEq < 0) { // 如果在爱心内部,则向中心吸引 const forceDirectionX = dx / distance; const forceDirectionY = dy / distance; const force = (100 - distance) / 100; this.speedX -= forceDirectionX * force * 0.2; this.speedY -= forceDirectionY * force * 0.2; } // 更新位置 this.x += this.speedX; this.y += this.speedY; // 边界检查 if (this.x < 0 || this.x > canvas.width) { this.speedX *= -0.5; } if (this.y < 0 || this.y > canvas.height) { this.speedY *= -0.5; } } draw() { ctx.fillStyle = this.color; ctx.beginPath(); ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2); ctx.fill(); } } // 初始化粒子 function init() { for (let i = 0; i < particleCount; i++) { particles.push(new Particle()); } } // 动画循环 function animate() { ctx.clearRect(0, 0, canvas.width, canvas.height); // 更新和绘制所有粒子 for (let i = 0; i < particles.length; i++) { particles[i].update(); particles[i].draw(); } requestAnimationFrame(animate); } // 窗口大小改变时调整画布 window.addEventListener('resize', function() { canvas.width = window.innerWidth; canvas.height = window.innerHeight; }); init(); animate(); </script> </body> </html> ``` ## 代码说明 1. 这段代码创建了一个黑色的页面,上面有多个彩色粒子 2. 粒子会受到爱心形状的引力影响,逐渐形成爱心图案 3. 粒子在爱心内部时会受到向中心的引力,在外部则自由移动 4. 爱心形状是通过数学方程 `(x² + y² - 1)³ - x²y³ = 0` 定义的 ## 注意事项 1. 粒子数量(`particleCount`)可以根据性能需求调整,数值越大效果越密集但对性能要求越高 2. 爱心的大小和位置可以通过调整代码中的除数(如50)来改变 3. 粒子颜色范围目前设置为红色到粉色(`hsl(330-390, 100%, 50%)`),可以根据需要修改 [2025-04-23 08:29:48 | AI写代码神器 | 1035点数解答]

相关提问