在JavaScript中实现鼠标跟随的粒子效果,通常涉及到HTML5的Canvas API来绘制粒子,并使用JavaScript来更新粒子的位置,使其跟随鼠标移动。以下是这个效果的基础概念、优势、类型、应用场景以及实现方法:
mousemove
,用于获取鼠标在页面上的位置。以下是一个简单的鼠标跟随粒子效果的实现示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Mouse Follow Particles</title>
<style>
canvas {
display: block;
background: #000;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
class Particle {
constructor(x, y) {
this.x = x;
this.y = y;
this.vx = Math.random() * 2 - 1;
this.vy = Math.random() * 2 - 1;
this.size = Math.random() * 3 + 1;
this.color = `rgba(255, 255, 255, ${Math.random()})`;
}
update(mouse) {
let dx = mouse.x - this.x;
let dy = mouse.y - this.y;
let distance = Math.sqrt(dx * dx + dy * dy);
let forceDirectionX = dx / distance;
let forceDirectionY = dy / distance;
let force = (2000 - distance) / 2000;
let directionX = forceDirectionX * force * 0.6;
let directionY = forceDirectionY * force * 0.6;
if (distance < 100) {
this.vx -= directionX;
this.vy -= directionY;
}
this.x += this.vx;
this.y += this.vy;
if (this.size > 0.2) this.size -= 0.1;
}
draw() {
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fill();
}
}
let particles = [];
let mouse = { x: undefined, y: undefined };
canvas.addEventListener('mousemove', (event) => {
mouse.x = event.x;
mouse.y = event.y;
});
canvas.addEventListener('mouseout', () => {
mouse.x = undefined;
mouse.y = undefined;
});
function init() {
particles = [];
for (let i = 0; i < 100; i++) {
let x = Math.random() * canvas.width;
let y = Math.random() * canvas.height;
particles.push(new Particle(x, y));
}
}
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, canvas.width, canvas.height);
particles.forEach((particle, index) => {
if (particle.size <= 0.3) {
particles.splice(index, 1);
particles.push(new Particle(Math.random() * canvas.width, Math.random() * canvas.height));
}
particle.update(mouse);
particle.draw();
});
}
init();
animate();
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
init();
});
</script>
</body>
</html>
requestAnimationFrame
进行动画循环,更新和绘制所有粒子。这个示例展示了如何创建一个简单的鼠标跟随粒子效果,你可以根据需要调整参数,创造出不同的视觉效果。
领取专属 10元无门槛券
手把手带您无忧上云