1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
| <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>Canvas 粒子背景</title> <style> body, html { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; background-color: #343558; } canvas { display: block; } </style> </head> <body>
<canvas id="particleCanvas"></canvas>
<script> const canvas = document.getElementById('particleCanvas'); const ctx = canvas.getContext('2d'); let particles = []; let animationFrameId = null; let colorShift = 0;
class SimpleParticle { constructor(canvas) { this.canvas = canvas; this.x = Math.random() * canvas.width; this.y = Math.random() * (canvas.height * 4 / 7); this.size = Math.random() * 0.8 + 0.5; this.speedX = Math.random() * 0.2 + 1.2; this.speedY = (Math.random() - 0.5) * 0.1; this.color = this.getColor(); this.alpha = Math.random() * 0.5 + 0.3; }
getColor() { const colors = ['rgb(255,255,255)', 'rgb(255,250,240)', 'rgb(240,248,255)']; return colors[Math.floor(Math.random() * colors.length)]; }
resetPosition() { this.x = -this.size; this.y = Math.random() * this.canvas.height; }
update() { this.x += this.speedX; this.y += this.speedY; if (this.x > this.canvas.width || this.y < -this.size || this.y > this.canvas.height + this.size) { this.resetPosition(); } }
draw() { ctx.save(); ctx.globalAlpha = this.alpha; ctx.fillStyle = this.color; ctx.beginPath(); ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2); ctx.fill(); ctx.restore(); } }
const resizeCanvas = () => { canvas.width = window.innerWidth; canvas.height = window.innerHeight; initParticles(); };
const initParticles = () => { particles = []; for (let i = 0; i < 150; i++) { particles.push(new SimpleParticle(canvas)); } };
const animate = () => { colorShift = (colorShift + 0.0005) % 1; const wave = Math.sin(colorShift * Math.PI * 2) * 0.05; const gradient = ctx.createLinearGradient(0, canvas.height, 0, 0); gradient.addColorStop(Math.max(0, 0.01 + wave * 0.1), '#f5e1b0'); gradient.addColorStop(Math.max(0, 0.17 + wave * 0.25), '#eea4a0'); gradient.addColorStop(Math.max(0, 0.40 + wave * 0.1), '#d2698e'); gradient.addColorStop(Math.max(0, 0.60 + wave * 0.4), '#6e4e79'); gradient.addColorStop(Math.min(1, 0.85 + wave * 0.2), '#343558'); ctx.fillStyle = gradient; ctx.fillRect(0, 0, canvas.width, canvas.height);
particles.forEach(particle => { particle.update(); particle.draw(); });
animationFrameId = requestAnimationFrame(animate); };
window.addEventListener('resize', resizeCanvas); resizeCanvas(); animate();
</script> </body> </html>
|