以下是一个只用 HTML 生成爱心粒子效果的示例代码。虽然只用 HTML 无法完全实现复杂的动画效果,但可以借助 HTML 的 `<canvas>` 元素结合 JavaScript 来实现这个效果,以下代码将 HTML 和内联的 JavaScript 写在一起: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>爱心粒子效果</title> <style> /* 设置画布样式,使其充满整个屏幕 */ canvas { display: block; background-color: #000; } </style> </head> <body> <!-- 创建一个画布元素 --> <canvas id="canvas"></canvas> <script> // 获取画布元素 const canvas = document.getElementById('canvas'); // 获取 2D 绘图上下文 const ctx = canvas.getContext('2d'); // 设置画布宽度和高度为窗口的宽度和高度 canvas.width = window.innerWidth; canvas.height = window.innerHeight; // 粒子类 class Particle { constructor() { // 随机生成粒子的初始位置 this.x = Math.random() * canvas.width; this.y = Math.random() * canvas.height; // 随机生成粒子的速度 this.vx = (Math.random() - 0.5) * 2; this.vy = (Math.random() - 0.5) * 2; // 随机生成粒子的大小 this.size = Math.random() * 2 + 1; // 随机生成粒子的颜色,使用红色系 this.color = `rgba(255, ${Math.random() * 100 + 155}, ${Math.random() * 100 + 155}, 1)`; } // 更新粒子的位置 update() { this.x += this.vx; this.y += this.vy; // 当粒子超出画布边界时,重新设置其位置 if (this.x < 0 || this.x > canvas.width) { this.x = Math.random() * canvas.width; } if (this.y < 0 || this.y > canvas.height) { this.y = Math.random() * canvas.height; } } // 绘制粒子 draw() { ctx.beginPath(); ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2); ctx.fillStyle = this.color; ctx.fill(); } } // 创建粒子数组 const particles = []; // 粒子数量 const particleCount = 200; // 初始化粒子数组 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); } // 开始动画 animate(); // 当窗口大小改变时,更新画布大小 window.addEventListener('resize', function () { canvas.width = window.innerWidth; canvas.height = window.innerHeight; }); </script> </body> </html> ``` 额外需要注意的逻辑点 1. 粒子的速度和大小是随机生成的,在实际使用中可以根据需要调整随机范围,以达到不同的效果。 2. 当粒子超出画布边界时,会重新设置其位置,这可以避免粒子丢失,但可能会导致粒子在边界处突然消失又出现的现象,可以考虑添加一些过渡效果。 3. 动画循环使用了 `requestAnimationFrame` 函数,它会根据浏览器的刷新频率来调用动画函数,确保动画的流畅性,但在某些低性能设备上可能会出现卡顿现象,可以考虑降低粒子数量。 [2025-07-05 22:12:10 | AI写代码神器 | 982点数解答]