var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
canvas.width = document.documentElement.clientWidth;
canvas.height = document.documentElement.clientHeight;
//随机数函数
function rand(min,max){
return parseInt(Math.random()*(max-min+1)+min);
}
//完成小球的构造函数
function ball(){
var r = rand(1,25);
//圆的半径
this.r = r;
//圆心坐标x
this.x = rand(r,canvas.width-r);
//圆心坐标y
this.y = rand(r,canvas.height-r);
var spX = rand(1,6);
this.speedX = rand(1,3)==1 ? -spX:spX;
var spY = rand(1,6);
this.speedY = rand(1,3)==1 ? -spY:spY;
//颜色
this.color = 'rgba('+rand(0,255)+','+rand(0,255)+','+rand(0,255)+','+Math.random().toFixed(2)+')';
}
//画球
ball.prototype.draw = function(){
ctx.beginPath();
ctx.arc(this.x,this.y,this.r,0,Math.PI*2,false);
ctx.fillStyle = this.color;
ctx.closePath();
ctx.fill();
}
//球移动
ball.prototype.move = function (){
this.x+=this.speedX;
this.y+=this.speedY;
if (this.x>=canvas.width-this.r) {
this.speedX*=-1;
} else if(this.x<=this.r){
this.speedX*=-1;
}
if (this.y>=canvas.height-this.r) {
this.speedY*=-1;
} else if(this.y<=this.r){
this.speedY*=-1;
}
}
var arr = [];
for (var i=0;i<100;i++) {
var obj = new ball();
arr.push(obj);
}
function boom(){
canvas.width = document.documentElement.clientWidth;
canvas.height = document.documentElement.clientHeight;
ctx.clearRect(0,0,canvas.width,canvas.height);
for (var i=0;i arr[i].draw(); arr[i].move(); } //浏览器脉搏 window.requestAnimationFrame(boom); } boom();