JavaScript鼠标跟随粒子特效是一种常见的网页交互效果,通过JavaScript和CSS实现。当用户在页面上移动鼠标时,页面上的粒子会跟随鼠标移动,从而产生动态的视觉效果。
以下是一个简单的JavaScript鼠标跟随粒子特效的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mouse Follow Particles</title>
<style>
body {
margin: 0;
overflow: hidden;
background: #000;
}
.particle {
position: absolute;
width: 5px;
height: 5px;
border-radius: 50%;
background: #fff;
pointer-events: none;
}
</style>
</head>
<body>
<script>
const numParticles = 100;
const particles = [];
class Particle {
constructor(x, y) {
this.x = x;
this.y = y;
this.size = Math.random() * 3 + 1;
this.speedX = Math.random() * 3 - 1.5;
this.speedY = Math.random() * 3 - 1.5;
this.element = document.createElement('div');
this.element.classList.add('particle');
this.element.style.width = `${this.size}px`;
this.element.style.height = `${this.size}px`;
this.element.style.left = `${this.x}px`;
this.element.style.top = `${this.y}px`;
document.body.appendChild(this.element);
}
update(mouseX, mouseY) {
const dx = mouseX - this.x;
const dy = mouseY - this.y;
const distance = Math.sqrt(dx * dx + dy * dy);
const forceDirectionX = dx / distance;
const forceDirectionY = dy / distance;
const maxDistance = 100;
const force = (maxDistance - distance) / maxDistance;
const directionX = forceDirectionX * force * 10;
const directionY = forceDirectionY * force * 10;
if (distance < maxDistance) {
this.x -= directionX;
this.y -= directionY;
} else {
this.x += this.speedX;
this.y += this.speedY;
}
this.element.style.left = `${this.x}px`;
this.element.style.top = `${this.y}px`;
}
}
function init() {
for (let i = 0; i < numParticles; i++) {
const x = Math.random() * window.innerWidth;
const y = Math.random() * window.innerHeight;
particles.push(new Particle(x, y));
}
}
function animate(event) {
for (let i = 0; i < particles.length; i++) {
particles[i].update(event.clientX, event.clientY);
}
requestAnimationFrame(() => animate(event));
}
window.addEventListener('mousemove', animate);
init();
</script>
</body>
</html>
requestAnimationFrame
代替setInterval
。通过以上代码和解决方案,可以实现一个基本的鼠标跟随粒子特效,并解决常见的性能和视觉效果问题。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云