<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
background: #000;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
/**@type{HTMLCanvasElement}*/
const canvas = document.getElementById('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const ctx = canvas.getContext('2d')
const random = Symbol('random')
const arcArr =[]
ctx.save()
class Arc {
constructor(x, y) {
/**
* x轴位置
* y轴位置
* x轴方向移速
* y轴方向移速
* 透明度
* 透明度衰减值
* 随机圆的半径
* 随机圆得颜色
*/
this.x = x;
this.y = y;
this.speeedX = (Math.random() - 0.5) * 3;
this.speeedY = (Math.random() - 0.5) * 3;
this.opacity = 1 ;
this.opacitySpeed = 0.96;
this.r = this[random](10,18);
this.color = 'rgb(' + this[random](0, 255) + ',' + this[random](0, 255) + ',' + this[random](0, 255) + ')';
}
/**
* 绘制圆
*/
rendom(){
ctx.beginPath();
ctx.arc(this.x,this.y,this.r,0,Math.PI*2)
ctx.fillStyle = this.color;
ctx.globalAlpha = this.opacity;
// 设置多个圆形重叠时的样式,
ctx.globalCompositeOperation = 'lighter'
ctx.fill()
this.moveArc()
}
/**
* 获取两个数之间的随机数
*/
[random](min,max){
return Math.round(Math.random() * (max - min) + min )
}
/**
* 修改器坐标使圆移动
*/
moveArc(){
this.x += this.speeedX;
this.y += this.speeedY;
this.opacity *= this.opacitySpeed;
}
}
canvas.onmousemove = function(e){
arcArr.push(new Arc(e.clientX,e.clientY))
}
function render(){
// 清空画布
ctx.clearRect(0,0,canvas.width,canvas.height)
// 让圆移动,和圆何时彻底消失
for(let i = 0 ; i < arcArr.length; i++){
arcArr[i].rendom()
if(arcArr[i].opacity <0.05){
arcArr.splice(i,1)
}
}
// 在浏览器下次重绘之前调用render函数
requestAnimationFrame(render);
}
render()
</script>
</body>
</html>