直接上代码,简单
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>CanvasLove</title>
<style>
#canvas{
background-color: #000000;
}
</style>
</head>
<body>
<canvas id="canvas" ></canvas>
</body>
<script>
var canvas = document.getElementById('canvas') ;
var ctx = canvas.getContext('2d') ;
var w = window.innerWidth;
var h = window.innerHeight;
canvas.width=w;
canvas.height=h;
//创建小球对象
var aBubble=[]; //存放生成的球对象
function Bubble(){};
Bubble.prototype={
init:function(){
this.x=random(0,w);
this.y=random(0,h);
this.vX=random(-1,1);
this.vY=random(-1,1);
this.color="rgb("+Math.random()*255+","+Math.random()*255+","+Math.random()*255+")";
this.r=random(2,8);
},
draw:function(){
ctx.beginPath();
ctx.fillStyle=this.color;
ctx.arc(this.x,this.y,this.r,0,Math.PI*2);
ctx.fill();
},
move:function(){
this.x+=this.vX;
this.y+=this.vY;
if(this.x-this.r<0 || this.x+this.r>w){
this.vX=-this.vX;
this.vY=-this.vY;
}
if(this.y-this.r<0 || this.y+this.r>h){
this.vX=-this.vX;
this.vY=-this.vY;
}
this.draw();
}
}
function random(min,max){
return Math.random()*(max-min)+min;
}
function createBubble(num){
for(var i=0;i<num;i++){
var bubble=new Bubble();
bubble.init();
bubble.draw();
aBubble.push(bubble);
}
}
createBubble(520);
setInterval(function(){
ctx.clearRect(0,0,w,h);
for(var item of aBubble){
item.move();
}
},1000/60);
</script>
</html>