main.js
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
var width = canvas.width = window.innerWidth;
var height = canvas.height = window.innerHeight;
function Ball(x,y,velX,velY,color,size){
this.x =x ;
this.y = y;
this.velX = velX;
this.velY = velY;
this.color = color;
this.size = size;
}
//画出模型
var balls=[];
Ball.prototype.draw = function(){
ctx.beginPath();
ctx.fillStyle=this.color;
ctx.arc(this.x,this.y ,this.size,0,Math.PI*2);
ctx.fill();
};
Ball.prototype.sport = function(){
if((this.x+this.velX)>width || (this.x+this.velX)<0){
this.velX = -(this.velX);
}
if((this.y+this.velY)>height || (this.y +this.velY)<0){
this.velY = -(this.velY);
}
this.x = this.x + this.velX;
this.y = this.y + this.velY;
};
function loop(){
ctx.fillStyle = 'rgba(0,0,0,0.25)';
ctx.fillRect(0,0,width,height);
while(balls.length<25){
var ball = new Ball(Math.random()*width,Math.random()*height,
Math.random()*8+Math.random()*(-8),
Math.random()*8+Math.random()*(-8),
'rgb('+Math.random()*255+','
+Math.random()*255+','
+Math.random()*255
+')',Math.random()*20);
balls.push(ball);
}
for (var i = 0; i < balls.length; i++) {
balls[i].draw();
balls[i].sport();
}
requestAnimationFrame(loop);
}
loop();
ball.css
body{
align-items: center;
}
div{
margin: auto;
}
canvas{
text-align: center;
}
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<title></title>
<link rel="stylesheet" type="text/css" href="css/ball.css"/>
</head>
<body>
<div>
<canvas></canvas>
</div>
<script src="js/main.js"></script>
</body>
</html>
效果图:
增加碰撞
Ball.prototype.collison = function(){
for (var j = 0; j < balls.length; j++) {
if(!(this===balls[j])){
var dx = Math.abs(this.x-balls[j].x);
var dy = Math.abs(this.y-balls[j].y);
var dis = Math.sqrt(dx*dx + dy*dy);
var total = this.size+balls[j].size;
if(dis<total){
this.velX = -(this.velX) ;
balls[j].velX =- balls[j].velX;
this.velY = - (this.velY) ;
balls[j].velY = - balls[j].velY;
this.color = balls[j].color ='rgb('+Math.random()*255+','
+Math.random()*255+','
+Math.random()*255
+')';
}
}
}
};
for (var i = 0; i < balls.length; i++) {
balls[i].draw();
balls[i].sport();
balls[i].collison();
}