代码如下:
<canvas id="snow" width="1210" height="600"></canvas> <script> function snow(id='snow', opacity=0.8, backgroundColor='rgba(0, 0, 0, 1)') { var canvas = document.getElementById(id); if (!canvas) return; var ctx = canvas.getContext('2d'); function Flake() { this.x = Math.random() * canvas.width; this.y = Math.random() * canvas.height; this.radius = Math.random() * 3 + 1; this.speedY = Math.random() * 1 + 0.5; this.speedX = Math.random() * 2 - 1; this.opacity = Math.random() * (0.8 - 0.2) + 0.2; this.update = function() { this.y += this.speedY; if (this.y > canvas.height) { this.y = -this.radius; this.x = Math.random() * canvas.width; } this.x += this.speedX; if (this.x > canvas.width || this.x < 0) { this.x = Math.random() * canvas.width; } }; this.draw = function() { ctx.fillStyle = 'rgba(255, 255, 255, ' + (this.opacity * opacity) + ')'; ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false); ctx.fill(); ctx.closePath(); }; } var flakes = []; for (var i = 0; i < 200; i++) { flakes.push(new Flake()); } function animate() { // 设置背景颜色 ctx.fillStyle = backgroundColor; ctx.fillRect(0, 0, canvas.width, canvas.height); flakes.forEach(function(flake) { flake.update(); flake.draw(); }); requestAnimationFrame(animate); } animate(); } document.addEventListener('DOMContentLoaded', function(){ snow(undefined, 0.8, 'rgba(0, 0, 0, 1)'); // 全局透明度调节值和背景颜色 }); </script>
演示效果如下: