效果:
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Particle Animation</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="particle-canvas"></canvas>
<script>
// 获取Canvas元素和2D上下文
const canvas = document.getElementById('particle-canvas');
const ctx = canvas.getContext('2d');
// 设置Canvas的宽度和高度为窗口的宽度和高度
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 鼠标坐标
let mouseX = 0;
let mouseY = 0;
// 创建树叶粒子对象
class LeafParticle {
constructor(x, y) {
this.x = x;
this.y = y;
this.size = Math.random() * 3 + 2;
this.speedX = (Math.random() - 0.5) * 5;
this.speedY = (Math.random() - 0.5) * 5;
}
update() {
this.x += this.speedX;
this.y += this.speedY;
if (this.size > 0.2) this.size -= 0.1;
}
draw() {
const distanceToMouse = Math.sqrt((this.x - mouseX) ** 2 + (this.y - mouseY) ** 2);
const maxDistance = 100;
const colorIntensity = Math.min(1, 1 - distanceToMouse / maxDistance);
const gradient = ctx.createRadialGradient(this.x, this.y, 0, this.x, this.y, this.size);
gradient.addColorStop(0, `rgba(137, 247, 254, ${colorIntensity})`);
gradient.addColorStop(1, `rgba(102, 166, 255, ${colorIntensity * 0.8})`);
ctx.fillStyle = gradient;
ctx.strokeStyle = `rgba(137, 247, 254, ${colorIntensity})`;
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
}
// 创建多个树叶粒子
const leaves = [];
function createLeaves(e) {
mouseX = e.x;
mouseY = e.y;
for (let i = 0; i < 5; i++) {
leaves.push(new LeafParticle(mouseX, mouseY));
}
}
// 监听鼠标移动事件
window.addEventListener('mousemove', createLeaves);
// 动画循环
function animate() {
// 清空Canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 更新和绘制每个树叶粒子
for (let i = 0; i < leaves.length; i++) {
leaves[i].update();
leaves[i].draw();
}
// 移除透明度较低的树叶粒子
leaves.forEach((leaf, index) => {
if (leaf.size <= 0.2) {
leaves.splice(index, 1);
}
});
// 递归调用动画函数
requestAnimationFrame(animate);
}
// 启动动画
animate();
</script>
</body>
</html>