代码如下:
<canvas id="rain" width="1100" height="200"></canvas> <script> function rainWithBackground(id='rain', bgImageUrl=''){ // 添加背景图片URL参数 var canvas = document.getElementById(id); if(!canvas) return; var ctx = canvas.getContext('2d'); ctx.strokeStyle='rgba(255,255,255,0.5)'; ctx.lineWidth=1; // 加载背景图片 var backgroundImg = new Image(); backgroundImg.src = bgImageUrl; // 设置背景图片的源 // 确保图片加载完成后再开始动画 backgroundImg.onload = function() { function Create(){ this.width = 1; // 初始化随机值 this.init = function() { this.x = Math.random()*canvas.width; this.y = -10-Math.random()*100; this.s = 5+Math.random()*3; this.height = Math.random()*50; }; this.init(); // 雨线 this.render = function(){ ctx.beginPath(); ctx.moveTo(this.x, this.y); ctx.lineTo(this.x-this.height/6, this.y+this.height); ctx.stroke(); ctx.closePath(); this.y += this.s; this.x -= 1; if (this.y > canvas.height + 100) this.init(); } } var struct=[]; for(var i=0;i<100;i++){ struct[i] = new Create(); // 修正构造函数名称 } // 渲染雨和背景图 !function run(){ // 先绘制背景图片 ctx.drawImage(backgroundImg, 0, 0, canvas.width, canvas.height); struct.forEach(v=>{v.render()}); window.requestAnimationFrame(run); }(); }; } document.addEventListener('DOMContentLoaded', function(){ // 调用时传入背景图片的URL rainWithBackground('rain', 'banner.jpg'); }); </script>
演示效果如下: