<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#canvas{
margin: 100px;
}
</style>
</head>
<body>
<canvas id="canvas">本浏览器版本低了请升级</canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js"></script>
<script>
// 获取当前画布
const canvas =document.getElementById('canvas')
const ctx = canvas.getContext('2d')
canvas.width=1000
canvas.height=500
canvas.style.backgroundColor='#000000'
// 小球类
class Ball{
constructor(x,y,color){
this.x=x
this.y=y
this.color=color
this.r=40
}
// 绘制小球
reader(){
ctx.save()
ctx.beginPath()
ctx.arc(this.x,this.y,this.r,0,Math.PI*2)
ctx.fillStyle=this.color
ctx.fill()
ctx.restore()
}
}
//会移动的小球类 如果想要继承父的类的方法是 extends super
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
}
}
// 实例化小球
let ballAll = []
let colorAll = ['red' ,'orange' ,'green' ,'blue' ,'write' , 'pink']
// 监听鼠标移动
canvas.addEventListener('mousemove',function (e) {
ballAll.push(new MoveBall(e.offsetX,e.offsetY,colorAll[_.random(0,colorAll.length-1)]))
})
// 开启定时器
setInterval(function () {
// 清屏操作
ctx.clearRect(0,0,canvas.width,canvas.height)
// 绘制
for(let i=0;i<ballAll.length;i++){
ballAll[i].reader()
ballAll[i].update()
}
},50)
</script>
</body>
</html>