效果如下
比较简单就直接放代码吧
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>阁下</title>
<style>
html,
body {
margin: 0;
padding: 0;
height: 100%;
box-sizing: border-box;
}
#canvas {
background-color: rgba(200, 247, 239,0.3);
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var arr = [];
function resizeFn(){
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
resizeFn();
// 随机数
function getRandom(min,max){
return Math.floor(Math.random() * (max + 1 -min) + min);
}
canvas.addEventListener("mousemove",(e) => {
arr.push({
x:e.clientX,
y:e.clientY,
r:2,
ySpeed:getRandom(1,5),//小球纵轴方向移动的速度
speed:Math.random() * 0.4 + 0.2,//小球半径变化的速度
rMax:getRandom(8,12),//小球最大半径
})
})
// 绘制
function draw(item){
ctx.beginPath();
ctx.fillStyle = "rgba(230,241,247,1)";
ctx.strokeStyle = "rgba(152,198,224,0.8)";
ctx.arc(item.x,item.y,item.r,0,2 * Math.PI,false);
ctx.fill();
ctx.stroke();
}
// 更新
function update(){
if(arr.length == 0) return;
arr.forEach((item,i) => {
// 更新半径
item.r = item.r + item.speed;
if(item.r >= item.rMax) arr.splice(i,1);
// 更新y轴位置
item.y = item.y - item.ySpeed;
if(item.y + item.r < 0) arr.splice(i,1);
// 绘制更新后的小球
if(item) draw(item);
})
}
setInterval(() => {
// 清空画布
ctx.clearRect(0,0,canvas.width,canvas.height);
update();
},50)
</script>
</body>
</html>