<canvas id="canvas" width="300px" height="300px"></canvas> <script> var cancas=document.getElementById("canvas"); var context=canvas.getContext("2d"); //定义构造器 function Circle(){ this.x=Math.random()*canvas.width; this.y=10; //this.r=Math.random()*40+10; this.r=15; //绘制圆形方法 this.paint=function(){ context.globalAlpha=0.5; context.beginPath(); context.arc(this.x,this.y,this.r,0,Math.PI*2); context.fill(); } //控制圆形下落 this.step=function(){ this.y++; } } var circles=[]; //定义函数,创建圆形对象 function createCircles(){ var circle=new Circle(); circles[circles.length]=circle; } //绘制所有圆形 function paintCircles(){ for(var i=0;i<circles.length;i++){ circles[i].paint(); } } //控制所有圆形下落 function stepCircles(){ for(var i=0;i<circles.length;i++){ circles[i].step(); } } var myimg=new Image(); myimg.src="bg.jpg"; var time=0; //定义定时器,充分绘制圆形,并下落 setInterval(function(){ context.drawImage(myimg,0,0); time++; if(time%20==0){ createCircles(); } paintCircles(); stepCircles(); },10); </script>
<canvas id="canvas" width="300px" height="300px"></canvas>