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

3D爱心粒子全屏跳动代码完整版

以下是一个使用 HTML、CSS 和 JavaScript 实现 3D 爱心粒子全屏跳动效果的完整代码示例: HTML 代码(`index.html`) ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>3D Heart Particles</title> <link rel="stylesheet" href="styles.css"> </head> <body> <canvas id="canvas"></canvas> <script src="script.js"></script> </body> </html> ``` CSS 代码(`styles.css`) ```css body { margin: 0; padding: 0; overflow: hidden; } canvas { display: block; width: 100%; height: 100vh; background-color: #000; } ``` JavaScript 代码(`script.js`) ```javascript // 获取 canvas 元素和其 2D 上下文 const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // 设置 canvas 的宽度和高度为窗口的宽度和高度 canvas.width = window.innerWidth; canvas.height = window.innerHeight; // 粒子数组 const particles = []; // 粒子数量 const particleCount = 300; // 定义爱心函数 function heart(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); return [x, y]; } // 粒子类 class Particle { constructor() { // 随机生成一个角度 const t = Math.random() * 2 * Math.PI; // 根据爱心函数计算初始位置 const [x, y] = heart(t); // 初始位置,按比例缩放并居中 this.x = (x * 10) + canvas.width / 2; this.y = (-y * 10) + canvas.height / 2; // 随机速度 this.vx = (Math.random() - 0.5) * 3; this.vy = (Math.random() - 0.5) * 3; // 随机颜色 this.color = `hsl(${Math.random() * 360}, 100%, 50%)`; // 随机大小 this.size = Math.random() * 3 + 1; } // 更新粒子的位置 update() { this.x += this.vx; this.y += this.vy; // 反弹效果,当粒子碰到边界时改变速度方向 if (this.x < 0 || this.x > canvas.width) { this.vx = -this.vx; } if (this.y < 0 || this.y > canvas.height) { this.vy = -this.vy; } } // 绘制粒子 draw() { ctx.beginPath(); ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2); ctx.fillStyle = this.color; ctx.fill(); } } // 初始化粒子 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++) { const particle = particles[i]; // 更新粒子位置 particle.update(); // 绘制粒子 particle.draw(); } // 请求下一帧动画 requestAnimationFrame(animate); } // 开始动画 animate(); // 窗口大小改变时更新 canvas 大小 window.addEventListener('resize', () => { canvas.width = window.innerWidth; canvas.height = window.innerHeight; }); ``` 额外注意的逻辑点 1. 爱心函数的参数 `t` 控制了爱心的形状和粒子的分布,若要改变爱心的大小,可以调整 `heart` 函数中返回的坐标的缩放比例。 2. 粒子的反弹效果是通过检查粒子的位置是否超出画布边界来实现的,若要实现不同的边界处理逻辑(如粒子消失后重新生成),可以修改 `update` 方法中的边界检查部分。 3. 随机颜色是通过 `hsl` 颜色模式生成的,若要改变颜色的范围或样式,可以调整 `hsl` 函数中的参数。 [2025-07-03 22:43:42 | AI写代码神器 | 1126点数解答]

相关提问