<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body{
margin: 100px;
}
#canvas{
box-shadow: 0 0 10px #000;
}
</style>
</head>
<body>
<canvas id="canvas">
</canvas>
<script>
//处理画布
const canvas=document.getElementById("canvas")
const clx=canvas.getContext('2d')
canvas.width=1000
canvas.height=600
canvas.style.backgroundColor='#000'
//创建小球类
class ball{
constructor(x,y,color){
this.x=x
this.y=y
this.color=color
this.r=40
}
render(){
clx.save()
clx.beginPath()
clx.arc(this.x,this.y,this.r,0,Math.PI*2)
clx.fillStyle=this.color
clx.fill()
clx.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(1,3)
}
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','green','blue','yellow','purple','pink']
//监听鼠标移动
canvas.addEventListener('mousemove',(e)=>{
let moveBall= new MoveBall(e.offsetX,e.offsetY,colorArr[_.random(0,colorArr.length-1)])
ballArr.push(moveBall)
console.log(ballArr);
})
setInterval(()=>{
//清除之前的
clx.clearRect(0,0,canvas.height,canvas.width)
//绘制
for(let i=0;i<ballArr.length;i++){
ballArr[i].render()
ballArr[i].update()
}
},50)
</script>
七彩小球
猜你喜欢
转载自blog.csdn.net/weixin_43453916/article/details/88019566
今日推荐
周排行