排版(布局)
<body>
<canvas id="cc" width="" height=""></canvas>
</body>
css样式
<style type="text/css">
*{
margin: 0;
padding: 0;
}
body{
background-color: black;
}
</style>
js代码
<script type="text/javascript">
var myCanvas = document.querySelector("#cc");
var ctx = myCanvas.getContext("2d");
myCanvas.width = document.documentElement.clientWidth;
myCanvas.height = document.documentElement.clientHeight;
function Ball(x,y){
this.x = x;
this.y = y;
this.r = 30;
this.color = "rgb("+Math.floor(Math.random()*255)+","+Math.floor(Math.random()*255)+","+Math.floor(Math.random()*255)+")";
this.dx = parseInt(Math.random()*15)-4;
this.dy = parseInt(Math.random()*15)-4;
ballarr.push(this);
}
Ball.prototype.reder = function(){
ctx.beginPath();
ctx.arc(this.x,this.y,this.r,0,2*Math.PI,true);
ctx.closePath();
ctx.fillStyle = this.color;
ctx.fill();
}
Ball.prototype.update = function(){
this.x += this.dx;
this.y += this.dy;
this.r--;
if(this.r < 0){
this.godie();
}
}
Ball.prototype.godie = function(){
for(var i = 0; i < ballarr.length;i++){
if(ballarr[i] === this){
ballarr.splice(i,1);
}
}
}
var ballarr = [];
myCanvas.onmousemove = function(){
new Ball(event.clientX,event.clientY);
}
setInterval(function(){
ctx.clearRect(0,0,myCanvas.width,myCanvas.height);
for(var i = 0; i < ballarr.length; i++){
ballarr[i].update();
ballarr[i] && ballarr[i].reder();
}
},20)
</script>
效果图
![在这里插入图片描述](https://img-blog.csdnimg.cn/20201104101926158.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ1NjY2ODM3,size_16,color_FFFFFF,t_70#pic_center)