canvas 四处乱窜的小球

QQ20171227-203915-HD.gif

1. 画球的方法；

2. 球移动的方法；

```// 定义一个球的构造函数
function Boll(x,y,r,color,speedx,speedy){
this.x = x;  this.y = y;  this.r = r;  this.color = color;
this.speedx = speedx;   this.speedy = speedy;
}
// 画的方法
Boll.prototype.draw = function(){
context.beginPath();
context.arc(this.x,this.y,this.r,0,Math.PI*2);
context.fillStyle = this.color;
context.fill();
}
// 球的移动方法
Boll.prototype.move = function(){
this.x += this.speedx;
this.y += this.speedy;
// 碰壁检测
if(this.xcanvas.width-this.r){
this.speedx *= -1;
}
if(this.ycanvas.height-this.r){
this.speedy *= -1;
}
}```

```// 随机数函数
function randNum(min,max){
return parseInt(Math.random()*(max-min) + min) ;
}
// 随机颜色
function randColor(){
return "rgb("+randNum(0,256)+","+randNum(0,256)+","+randNum(0,256)+")";
}```

```var arr = [];
for(var i = 0 ; i < 100 ;i++){
var r = randNum(5,45);
var x = randNum(r,canvas.width-r);
var y = randNum(r,canvas.height-r);
var speedx = randNum(1,4);
var speedy = randNum(1,4);
var color = randColor();
var newboll = new Boll(x,y,r,color,speedx,speedy);
arr.push(newboll);
}```

window.requestAnimationFrame：

```function act(){
context.clearRect(0,0,canvas.width,canvas.height);
for(var i = 0 ; i < arr.length ; i++){
arr[i].draw();
arr[i].move();
}
window.requestAnimationFrame(act);
}
act();```

|