<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>ball</title>
<style>
body,html{
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
#canvas { border: 1px solid #aaaaaa; display: block; margin: 50px auto; background: #000;}
</style>
</head>
<body>
<div id="canvas-warp">
<canvas id="canvas" width="" height="">
你的浏览器居然不支持Canvas?!赶快换一个吧!!
</canvas>
</div>
<script>
var docW = document.body.clientWidth;
var dovH = document.body.clientHeight;
var canvas = document.getElementById('canvas');
canvas.width=docW;
canvas.height=dovH;
var context = canvas.getContext('2d');
var cw = docW;
var ch = dovH;
var arrBig = [];
var arrSmall=[];
var fn = {
getX:function(){
return 100+Math.floor(Math.random()*(cw-200));
},
getSpeed:function(){
return Math.floor(Math.random()*5+10);
},
getClolr:function(){
var r = Math.floor(Math.random()*255);
var g = Math.floor(Math.random()*255);
var b = Math.floor(Math.random()*255);
var c = "rgba("+r+","+g+","+b+",1)";
var dx = Math.floor(Math.random()*10)-5;
var dy = Math.floor(Math.random()*10)-5;
return {
dx,dy,c
}
}
}
setInterval(() => {
context.clearRect(0, 0, docW, dovH);
if(arrBig.length<30){
arrBig.push(new Big(fn.getX(),ch-10,cw,ch,fn.getSpeed()))
}
for(var i=0;i<arrBig.length;i++){
arrBig[i].update();
if(arrBig[i]){
arrBig[i].draw();
}
}
for(var i=0;i<arrSmall.length;i++){
arrSmall[i].update();
if(arrSmall[i]){
arrSmall[i].draw();
}
}
}, 30);
function Big(x,y,w,h,s){
this.w = w;
this.h = h;
this.x = x;
this.y = y;
this.s= s;
arrBig.push(this);
}
Big.prototype={
init:function(){
},
draw:function(){
context.fillStyle='#fff';
context.fillRect(this.x,this.y,2,5);
},
update:function(){
if(this.y<150){
this.remove();
for(var i=0;i<30;i++){
new Small(this.x,this.y,fn.getClolr().c,fn.getClolr().dx,fn.getClolr().dy).draw();
}
}else{
this.y-=this.s;
}
},
remove:function(){
for(var i=0;i<arrBig.length;i++){
if(arrBig[i] == this){
arrBig.splice(i,1);
}
}
}
}
for(var i=0;i<30;i++){
new Big(fn.getX(),ch-10,cw,ch,fn.getSpeed())
}
function Small(x,y,c,dx,dy){
this.x=x;
this.y=y;
this.c=c;
this.dx = dx;
this.dy = dy;
arrSmall.push(this);
}
Small.prototype={
draw:function(){
context.beginPath();
context.arc(this.x,this.y,2,Math.PI*2,false);
context.fillStyle=this.c;
context.fill();
},
update:function(){
this.x+=this.dx;
this.y+=this.dy;
if(Math.abs(this.dy)>10 || Math.abs(this.dx)>8){
this.remove();
}else{
this.dy+=0.2;
}
},
remove:function(){
for(var i=0;i<arrSmall.length;i++){
if(arrSmall[i] == this){
arrSmall.splice(i,1);
}
}
}
}
</script>
</body>
</html>