var myCanvas = document.getElementById("cont");
var txt = myCanvas.getContext("2d");
//获取canvas宽高
var cw = myCanvas.width;
var ch = myCanvas.height;
//随机函数
function randNum(min, max) {
return parseInt(Math.random() * (max - min + 1) + min);
}
//定义一个球类
function Ball() {
//定义圆的半径
this.r = randNum(10, 50);
//定义球的圆心位置
this.x = randNum(this.r, cw - this.r);
this.y = randNum(this.r, ch - this.r);
//定义球的颜色
this.color = "rgb(" + randNum(0, 255) + "," + randNum(0, 255) + "," + randNum(0, 255) + ")";
//定义速度
this.speedX = randNum(-5, 5) || 1;
this.speedY = randNum(-5, 5) || 1;
//画的方法
this.draw = function() {
txt.beginPath();
txt.arc(this.x, this.y, this.r, 0, Math.PI * 2, true);
txt.fillStyle = this.color;
txt.fill();
}
}
//球原型的方法通过类的原型追加
Ball.prototype.move = function() {
this.x += this.speedX;
this.y += this.speedY;
//边界值判断
if (this.x <= this.r || this.x >= cw - this.r) {
this.speedX *= -1;
}
if (this.y <= this.r || this.y >= ch - this.r) {
this.speedY *= -1;
}
}
//定义一个数组,去存储多个球的信息
var ballArr = [];
for (var i = 0; i < 100; i++) {
var ball = new Ball();
ballArr.push(ball);
}
console.log(ballArr);
//动画函数
function animate() {
//清画布
txt.clearRect(0, 0, cw, ch);
for (var i = 0; i < ballArr.length; i++) {
ballArr[i].draw();
ballArr[i].move();
}
window.requestAnimationFrame(animate);
}
animate();