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

编写一个粒子樱花代码

# 粒子樱花效果代码 以下是一个使用HTML5 Canvas创建的粒子樱花效果代码: ```html <!DOCTYPE html> <html> <head> <title>粒子樱花效果</title> <style> body { margin: 0; overflow: hidden; background: linear-gradient(to bottom, #1a2a6c, #b21f1f, #fdbb2d); } canvas { display: block; } </style> </head> <body> <canvas id="canvas"></canvas> <script> const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // 设置画布大小为窗口大小 canvas.width = window.innerWidth; canvas.height = window.innerHeight; // 樱花粒子数组 let particles = []; const particleCount = 100; // 樱花颜色 const colors = [ '#FFC0CB', // 粉红 '#FFB6C1', // 浅粉红 '#FF69B4', // 热粉红 '#FF1493', // 深粉红 '#DB7093' // 苍紫红 ]; // 粒子类 class Particle { constructor() { this.x = Math.random() * canvas.width; this.y = Math.random() * canvas.height * -1; this.size = Math.random() * 5 + 2; this.speedX = Math.random() * 3 - 1.5; this.speedY = Math.random() * 3 + 1; this.color = colors[Math.floor(Math.random() * colors.length)]; this.rotation = Math.random() * 360; this.rotationSpeed = Math.random() * 2 - 1; this.opacity = Math.random() * 0.5 + 0.5; } update() { this.rotation += this.rotationSpeed; this.x += this.speedX; this.y += this.speedY; // 如果粒子超出底部边界,重新从顶部开始 if (this.y > canvas.height) { this.y = Math.random() * canvas.height * -1; this.x = Math.random() * canvas.width; } } draw() { ctx.save(); ctx.translate(this.x, this.y); ctx.rotate(this.rotation * Math.PI / 180); ctx.globalAlpha = this.opacity; // 绘制樱花花瓣(简化版) ctx.beginPath(); ctx.moveTo(0, 0); ctx.bezierCurveTo(this.size/2, -this.size/2, this.size, 0, 0, this.size); ctx.bezierCurveTo(-this.size, 0, -this.size/2, -this.size/2, 0, 0); ctx.fillStyle = this.color; ctx.fill(); ctx.restore(); } } // 初始化粒子 function init() { particles = []; 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. 这段代码创建了一个HTML5 Canvas动画,模拟樱花飘落的效果 2. 每个樱花粒子有自己的位置、大小、速度、颜色和旋转属性 3. 使用贝塞尔曲线绘制简单的樱花花瓣形状 4. 当粒子飘出屏幕底部时,会从顶部重新出现 5. 设置为渐变色模拟天空效果 ## 自定义建议 1. 调整`particleCount`变量可以改变樱花数量 2. 修改`colors`数组可以改变樱花颜色 3. 调整`speedX`和`speedY`的范围可以改变飘落速度和方向 4. 可以添加鼠标交互效果,使樱花围绕鼠标飘动 ## 注意事项 1. 粒子系统性能与粒子数量直接相关,过多粒子可能导致性能下降 2. 贝塞尔曲线绘制的花瓣是简化版,可以替换为更复杂的花瓣形状 3. 在移动设备上可能需要调整粒子数量和大小以获得最佳性能 [2025-03-31 15:04:07 | AI写代码神器 | 1043点数解答]

相关提问