canvas小游戏
过完春节回来一直没事情干,无聊到了一种境界,摸鱼摸着摸着突然想写两行代码,然后就有了这个无聊的玩意.....
贴下代码吧..
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<style>
body{
background-color: #000000;
margin: 0px;
overflow: hidden;
}
.btn{
color: #fff;
cursor: pointer;
}
</style>
<body>
<div id="add" class="btn">添加小球</div>
</body>
<script>
document.getElementById('add').onclick = function () {
let ball = new Ball()
ballArr.push(ball)
}
document.body.onclick = function(event) {
let x = event.clientX ,
y = event.clientY;
ballArr.map((i)=>{
if(i.x-i.r<=x && x<= i.x && y>=i.y-i.r && y<= i.y){
i.speedX += 1;
i.speedY += 1;
}else if( x<=i.x+i.r && x>= i.x && y>=i.y-i.r && y<= i.y){
i.speedX -= 1;
i.speedY += 1
}else if( x<=i.x+i.r && x>= i.x && y<= i.y+i.r && y>= i.y){
i.speedX -= 1;
i.speedY -= 1
}else if( i.x-i.r<=x && x<= i.x && y<= i.y+i.r && y>= i.y){
i.speedX += 1;
i.speedY -= 1
}
})
};
var W = window.innerWidth,
H = window.innerHeight,
canvas = document.createElement('canvas'),
context = canvas.getContext('2d');
document.body.appendChild(canvas);
canvas.width = W;
canvas.height = H;
function randNum(min,max) {
return parseInt(Math.random() * (max - min + 1) + min);
}
function Ball() {
this.r = randNum(30,70)
this.x = randNum(this.r,W - this.r);
this.y = randNum(this.r,H - this.r);
this.color = getColor()
this.speedX = 0
this.speedY = 0
this.draw = function () {
context.beginPath()
context.arc(this.x,this.y,this.r,0,Math.PI*2)
context.fillStyle = this.color
context.fill()
}
}
Ball.prototype.move = function () {
this.x += this.speedX;
this.y += this.speedY;
if(this.x <= this.r || this.x >= W - this.r){
this.speedX *= -1;
}
if(this.y <= this.r || this.y >= H - this.r){
this.speedY *= -1;
}
}
var ballArr = []
function animate(){
context.clearRect(0,0,W,H)
ballArr.map((i)=>{
i.draw()
i.move()
})
for(i=0;i<=ballArr.length;i++){
for(j=i+1;j<ballArr.length;j++){
let dx = ballArr[i].x - ballArr[j].x
let dy = ballArr[i].y - ballArr[j].y
let dd = Math.sqrt(dx*dx + dy*dy)
if(dd <= ballArr[i].r + ballArr[j].r){
if(ballArr[i].r>10){
ballArr[i].r -= 3;
}else{
ballArr[i].r += randNum(5,50) ;
}
if(ballArr[j].r>10){
ballArr[j].r -= 3;
}else{
ballArr[j].r += randNum(5,50) ;
}
ballArr[i].speedX = -ballArr[i].speedX + randNum(-2,2)
ballArr[i].speedY = -ballArr[i].speedY + randNum(-2,2)
ballArr[j].speedX = -ballArr[j].speedX + randNum(-2,2)
ballArr[j].speedY = -ballArr[j].speedY + randNum(-2,2)
ballArr[i].color = getColor()
ballArr[j].color = getColor()
}
}
}
requestAnimationFrame(animate)
}
animate()
function getColor(){
var color="#";
for(var i=0;i<6;i++){
color += (Math.random()*16 | 0).toString(16);
}
return color;
}
</script>
</html>