<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>躁动的小球</title>
<style media="screen">
*{
margin: 0px;
padding: 0px;
}
#canvas{
box-shadow: 0px 0px 10px black;
display: block;
margin: 50px auto;
background: black;
}
</style>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
</body>
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
//随机函数
function randomSize(min,max){
return Math.floor(Math.random()*(max -min)+min);
}
function randomColor(){
var r = randomSize(0,255);
var g = randomSize(0,255);
var b = randomSize(0,255);
return "rgb(" + r +"," + g + "," + b+")";
}
//创建小球对象
function Ball(){
var speedX,speedY;
//速度
speedX = randomSize(1,6);
speedY = randomSize(1,6);
//半径
this.r = randomSize(5,8);
//圆心
this.x = randomSize(this.r,canvas.width-this.r);
this.y = randomSize(this.r,canvas.height -this.r);
//方向
this.speedX = randomSize(1,3) == 1 ? speedX : -speedX;
this.speedY = randomSize(1,3) == 1 ? speedY : -speedY;
//颜色
this.color = randomColor();
}
//定义方法绘制小球
Ball.prototype.draw = function(){
ctx.beginPath();
ctx.arc(this.x,this.y,this.r,0,360);
ctx.closePath();
ctx.fillStyle = this.color;
ctx.fill();
}
//定义方法完成小球的移动
Ball.prototype.move = function (){
//改变中心的的x,y
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 balls = [];
for (var i = 0; i < 200; i++) {
var ball = new Ball();
balls.push(ball);
}
//让小球骚动起来
function animation(){
//每次动起来之前,清理之前的小球
ctx.clearRect(0,0,canvas.width,canvas.height);
//遍历小球数组,让每一个小球动起来
for (var i = 0; i < balls.length; i++) {
balls[i].move();
balls[i].draw();
};
window.requestAnimationFrame(animation);
}
animation();
</script>
</html>
躁动的小球
最新推荐文章于 2021-05-27 05:27:48 发布