酷代码 AI
菜单
服务商

用html做一个爱心粒子跳动代码,爱心呈现粉红色,以粒子的形态慢慢形成爱心的形状,最后爱心在跳动,慢慢旋转。

以下是一个使用 HTML、CSS 和 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(x, y) { // 粒子的初始 x 坐标 this.x = x; // 粒子的初始 y 坐标 this.y = y; // 粒子的目标 x 坐标 this.targetX = x; // 粒子的目标 y 坐标 this.targetY = y; // 粒子的半径 this.radius = Math.random() * 2 + 1; // 粒子的颜色,粉红色 this.color = 'rgba(255, 192, 203, 1)'; // 粒子的速度 this.speed = 0.05; } // 更新粒子的位置 update() { // 计算粒子当前位置与目标位置的差值 const dx = this.targetX - this.x; const dy = this.targetY - this.y; // 根据速度更新粒子的 x 坐标 this.x += dx * this.speed; // 根据速度更新粒子的 y 坐标 this.y += dy * this.speed; } // 绘制粒子 draw() { ctx.beginPath(); // 绘制一个圆形代表粒子 ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2); ctx.fillStyle = this.color; ctx.fill(); } } // 生成爱心形状的坐标 function generateHeartCoordinates() { const points = []; for (let t = 0; t < 2 * Math.PI; t += 0.01) { // 爱心曲线的参数方程计算 x 坐标 const x = 16 * Math.pow(Math.sin(t), 3); // 爱心曲线的参数方程计算 y 坐标 const y = - (13 * Math.cos(t) - 5 * Math.cos(2 * t) - 2 * Math.cos(3 * t) - Math.cos(4 * t)); // 将坐标转换到画布中心并放大 const canvasX = canvas.width / 2 + x * 10; const canvasY = canvas.height / 2 + y * 10; points.push({ x: canvasX, y: canvasY }); } return points; } // 初始化粒子数组 const particles = []; const heartCoordinates = generateHeartCoordinates(); heartCoordinates.forEach(coord => { // 随机初始化粒子的位置 const randomX = Math.random() * canvas.width; const randomY = Math.random() * canvas.height; particles.push(new Particle(randomX, randomY)); particles[particles.length - 1].targetX = coord.x; particles[particles.length - 1].targetY = coord.y; }); // 定义旋转角度 let rotation = 0; // 定义跳动的幅度 let beat = 0; // 动画循环函数 function animate() { // 清除画布 ctx.clearRect(0, 0, canvas.width, canvas.height); // 更新旋转角度 rotation += 0.002; // 更新跳动幅度 beat = Math.sin(Date.now() * 0.005) * 5; // 保存当前画布状态 ctx.save(); // 将画布原点移动到画布中心 ctx.translate(canvas.width / 2, canvas.height / 2); // 旋转画布 ctx.rotate(rotation); // 将画布原点移回原来的位置 ctx.translate(-canvas.width / 2, -canvas.height / 2); // 更新并绘制每个粒子 particles.forEach(particle => { particle.update(); particle.draw(); }); // 恢复画布状态 ctx.restore(); // 请求下一帧动画 requestAnimationFrame(animate); } // 开始动画 animate(); </script> </body> </html> ``` 我在以往的开发过程中,碰到过以下几点需要格外小心处理的地方: 1. 注意粒子的速度设置,速度过快可能导致粒子直接跳到目标位置,没有形成慢慢移动的效果;速度过慢则动画会显得卡顿。 2. 旋转和跳动的幅度参数需要根据实际效果进行调整,不合适的参数可能会让动画效果不自然。 3. 当窗口大小改变时,需要重新计算爱心的坐标和画布的大小,否则可能会出现爱心位置偏移或显示不全的问题。 [2025-12-03 15:26:13 | AI写代码神器 | 1282点数解答]

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