<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>多个圆从上二下掉落</title>
</head>
<body>
<canvas id="canvas" width="406px" height="300px"></canvas>
</body>
<script>
var canvas=document.getElementById("canvas");
var context=canvas.getContext("2d");//创建画布对象
var img=new Image();//创建圆心的背景图片
img.src="bg.png";
//创建一个圆形对象
function Circle(){
this.r=Math.floor(Math.random()*6+5);//圆的半径从5-10
this.x=Math.random()*(canvas.width-2*this.r+1)+this.r;//横坐标最小值是0+radius,最大值是长度-radius,可以不取整
this.y=0;
this.red=parseInt(Math.random()*256);
this.g=parseInt(Math.random()*256);
this.b=parseInt(Math.random()*256);
if(! Circle.prototype.paint) {//在原型对象中添加方法,可以节省内存
Circle.prototype.paint = function () {
//创建路径的方式创建一个圆形
context.fillStyle="rgb("+this.red+","+this.g+","+this.b+")";
context.beginPath();
context.arc(this.x,this.y,this.r,0,Math.PI*2);
context.fill();
}
}
if(!Circle.prototype.step){
Circle.prototype.step=function(){
this.y+=10;
}
}
}
var circles=[];//创建一个放置圆形的数组,数组中是多个圆形对象
function CreateCircle(){//创建圆形对象
var circle=new Circle();
circles.push(circle);//将创建的圆形对象添加到数组中
}
function PaintCircle(){//遍历数组对象绘制所有的圆形
for(var i=0;i<circles.length;i++){
circles[i].paint();
}
}
function StepCircle() {//遍历数组将所有图形下移
for(var i=0;i<circles.length;i++){
circles[i].step();
}
}
var timer=0;
setInterval(function(){
timer++;
//先绘制背景图,再绘制圆,在移动圆,最后继续创建圆
context.drawImage(img,0,0);
PaintCircle();
StepCircle();
if(timer%5==0){
CreateCircle();
}
},100)
</script>
</html>
绘制的是圆形自上而下掉落,原来的圆形并没有消失,只是用背景图遮盖了,每一次都是重新绘制,先绘制背景图,后绘制圆形,注意,在绘制的过程中,当背景图片加载结束后,才可以
在上面绘制圆形,否则错误,可以使用onload事件.