canvas画布实现创建20个小球,小球在画布内碰壁反弹 <!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
#cv{
border:1px solid;
}
</style>
</head>
<body>
<canvas id="cv" width="500" height="500"></canvas>
</body>
<script type="text/javascript">
var ctx = cv.getContext("2d");
function Arc(x,y,r,d="0",z=Math.PI*2,color,s,s1){
this.x=x;
this.y=y;
this.r=r;
this.d=d;
this.z=z;
this.color=color;
this.s=s;
this.s1=s1;
}
Arc.prototype.draw =function(){
ctx.beginPath();
ctx.moveTo(this.x,this.y);
ctx.arc(this.x,this.y,this.r,this.d,this.z,this.color,this.s,this.s1);
ctx.fillStyle=this.color;
ctx.fill();
}
//生成随机数
function randomNum(min,max){
return parseInt(Math.random()*(max-min+1)+min);
}
//生成随机颜色
function randomColor(){
return "rgb("+Math.floor(Math.random()*256)+","+Math.floor(Math.random()*256)+","+Math.floor(Math.random()*256)+")";
}
var arr =[];
function createbox(){
for(var i=0;i<20;i++){
var box = new Arc(randomNum(20,300),randomNum(20,300),randomNum(10,30),0,Math.PI*2,randomColor(),randomNum(-7,20),randomNum(-7,20));
box.draw();
arr.push(box);
}
return box;
}
createbox();
//小球碰壁反弹
setInterval(function(){
cv.width=cv.width;
for(var i =0;i<arr.length;i++){
arr[i].x+=arr[i].s;
if(arr[i].x>=cv.width-arr[i].r){
arr[i].s*=-1;
}
if(arr[i].x-arr[i].r<=0){
arr[i].s*=-1;
}
arr[i].y+=arr[i].s1;
if(arr[i].y>=cv.height-arr[i].r){
arr[i].s1*=-1;
}
if(arr[i].y-arr[i].r<=0){
arr[i].s1*=-1;
}
arr[i].draw();
}
},50)
</script>
</html>