**
运用ES6制作绚丽的小球
**
代码展示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="../underscore.js"></script>
<style>
#canvas{
margin: auto 0;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const canvas=document.getElementById("canvas");
const ctx=canvas.getContext("2d");
canvas.width=1500;
canvas.height=1000;
canvas.style.backgroundColor="black"
class ball{
constructor(x,y,color){
this.x=x;
this.y=y;
this.color=color;
this.r=40;
}
render(){
ctx.save();
ctx.beginPath();
ctx.arc(this.x,this.y,this.r,0,Math.PI*2);
ctx.fillStyle=this.color;
ctx.fill();
ctx.restore();
}
}
//会移动的小球类
class moveBall extends ball{
constructor(x,y,color){
super(x,y,color);
//量的变化
this.dX=_.random(-5,5);
this.dY=_.random(-5,5);
this.dr=_.random(3,5);
}
upDate(){
this.x+=this.dX;
this.y+=this.dY;
this.r-=this.dr;
if(this.r<0){
this.r=0;
}
}
}
//实例化小球
let ballArr=[];
let colorArr=["red","white","orange","pink","green","blue","yellow"];
//监听鼠标的移动
canvas.addEventListener("mousemove",function (e) {
e=e||event;
ballArr.push(new moveBall(e.offsetX,e.offsetY,colorArr[_.random(0,colorArr.length-1)]));
})
//开启定时器
setInterval(function () {
ctx.clearRect(0,0,canvas.width,canvas.height);
for(let i=0;i<ballArr.length;i++){
ballArr[i].render();
ballArr[i].upDate();
}
},50)
</script>
</body>
</html>