<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>滚动的小球 原型链</title>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="text/javascript">
let canvas=document.getElementById("canvas");
let ctx=canvas.getContext("2d");
canvas.width=1000;
canvas.height=500;
canvas.style.backgroundColor="#000";
// 绘制图形
function ball(x,y,color){
this.x=x;//x坐标
this.y=y;//y坐标
this.r=40;//半径
this.color=color;//颜色
}
ball.prototype={
constructor:ball,
rand(){
ctx.save();
ctx.beginPath();//绘制线段
ctx.arc(this.x,this.y,this.r,0,2*Math.PI);// 绘制圆
ctx.fillStyle=this.color;
ctx.fill();//填充路径
ctx.restore();
}
};
// 单个图形移动 并缩小
function moveBall(x,y,color){
this.zx=5-Math.random()*10; //x轴移动的量
this.zy=5-Math.random()-10;//y轴移动的量
this.zr=Math.random()*3+1;//r缩小的量
ball.call(this,x,y,color);
}
moveBall.prototype=new ball();
moveBall.prototype.constructor=moveBall;
moveBall.prototype.upBall=function(){
this.x+=this.zx;
this.y+=this.zy;
this.r-=this.zr;
// 当 半径小于0时,要判断
if(this.r<0){
this.r=0;
}
}
let colorArr=['red','blue','yellow','purple','pink','green'];// 生成
let moveB=[];
//跟随鼠标随机生成 小圆
canvas.addEventListener('mousemove',function(e){
let colorRam=Math.round(Math.random()*(colorArr.length-1));
moveB.push(new moveBall(e.pageX,e.pageY,colorArr[colorRam]));
})
// 添加定时器 每50调用一次
setInterval(function(){
// 清除画布
ctx.clearRect(0,0,1000,500);
for (var i = 0; i < moveB.length; i++) {
moveB[i].rand();
moveB[i].upBall();
}
},50)
</script>
</body>
</html>