多个小球运动c语言,canvas多个小球运动

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();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值