案例代码;
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>绚丽小球</title>
<style>
body{
margin: 150px;
}
#canvas{
margin: 100px auto;
box-shadow: 0 0 10px #000;
}
</style>
</head>
<body>
<canvas id="canvas">
当前的浏览器不支持该版本!
</canvas>
<script type="text/javascript" src="js/jquery.js" ></script>
<script type="text/javascript" src="js/underScore.js" ></script>
<script>
//1.获取当前画布
const canvas=document.getElementById("canvas");
//获取上下文
const ctx=canvas.getContext('2d');
//设置画布大小
canvas.width=1000;
canvas.height=600;
canvas.style.backgroundColor='#000';
//2.创建小球类
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();
}
}
//3.会移动的小球类(继承Ball)
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(1,3)
}
/*
* 动态更新数据
*/
upDate(){
this.x += this.dx;
this.y += this.dy;
this.r -= this.dr;
if(this.r < 0){
this.r=0;
}
}
}
//4.实例化小球
let ballArr=[];
let colorArr=['red','green','blue','yellow','purple','pink','orange'];
//5.监听鼠标移动
canvas.addEventListener('mousemove',function(e){
ballArr.push(new MoveBall(e.offsetX,e.offsetY,colorArr[_.random(0,colorArr.length-1)]));
console.log(ballArr);
});
//6.开启定时器
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);
let ball=new Ball(50,50,'red');
ball.render();
</script>
</body>
</html>
效果: