基础概念: 鼠标跟随粒子特效是一种常见的网页交互效果,它通过JavaScript和CSS实现,使得页面上的粒子元素能够跟随鼠标指针移动,从而增强用户的交互体验。
优势:
类型:
应用场景:
示例代码: 以下是一个简单的鼠标跟随粒子特效的JavaScript和HTML/CSS代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Mouse Follow Particles</title>
<style>
body {
margin: 0;
overflow: hidden;
}
.particle {
position: absolute;
width: 10px;
height: 10px;
border-radius: 50%;
background-color: #ff0000;
pointer-events: none;
}
</style>
</head>
<body>
<script>
const numParticles = 50;
const particles = [];
class Particle {
constructor() {
this.x = 0;
this.y = 0;
this.size = Math.random() * 5 + 5;
this.speedX = Math.random() * 3 - 1.5;
this.speedY = Math.random() * 3 - 1.5;
this.element = document.createElement('div');
this.element.className = 'particle';
this.element.style.width = `${this.size}px`;
this.element.style.height = `${this.size}px`;
document.body.appendChild(this.element);
}
update(mouse) {
const dx = mouse.x - this.x;
const dy = mouse.y - 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;
}
this.x += this.speedX;
this.y += this.speedY;
this.element.style.left = `${this.x}px`;
this.element.style.top = `${this.y}px`;
}
}
for (let i = 0; i < numParticles; i++) {
particles.push(new Particle());
}
document.addEventListener('mousemove', (event) => {
const mouse = { x: event.clientX, y: event.clientY };
particles.forEach(particle => particle.update(mouse));
});
</script>
</body>
</html>
常见问题及解决方法:
requestAnimationFrame
优化动画性能。requestAnimationFrame
优化动画性能。通过以上方法,可以有效实现并优化鼠标跟随粒子特效。
领取专属 10元无门槛券
手把手带您无忧上云