参考@叶建华 @www.IT666.com
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>绚丽小球</title>
<style>
*{
margin: 0;
padding: 0;
}
body{
margin: 50px;
}
#canvas{
/* margin: 100px auto;*/
box-shadow: 0 0 10px #000;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script src="lib/underscore-min.js"></script>
<script>
let canvas = document.getElementById('canvas');
const ctx = 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(){
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(1,3);
}
/** */
upDate(){
this.x +=this.dX;
this.y += this.dY;
this.r -= this.dR;
if(this.r<0){
this.r =0;
}
}
}
/* let ball = new Ball(50,50,'red');
ball.render();*/
let ballArr = [];
let colorArr = ['red','green','blue','yellow','purple','pink','orange'];
//监听鼠标事件
canvas.addEventListener('mousemove',function (e) {
var a= _.random(0,colorArr.length-1);
console.log(a);
let ball = new MoveBall(e.offsetX, e.offsetY,colorArr[a]);
ballArr.push(ball);
});
canvas.addEventListener('mouseout',function (e) {
setTimeout(function () {
ballArr = [];
},2000)
});
//开启定时器
setInterval(function () {
//清屏
ctx.clearRect(0, 0, canvas.width, canvas.height);
/** ball 对象不能无限的增长,性能问题*/
if(ballArr.length>1000){
ballArr = [];
}
for(let i=0; i<ballArr.length; i++){
ballArr[i].render();
ballArr[i].upDate();
}
},50);
</script>
</body>
</html>