基础概念: JavaScript粒子鼠标跟随是一种常见的网页交互效果,它通过在页面上创建一系列小粒子,并使这些粒子跟随鼠标移动,从而实现视觉上的动态效果。这种效果通常用于增强用户体验,使网站看起来更加生动和有趣。
优势:
类型:
应用场景:
示例代码: 以下是一个简单的JavaScript粒子鼠标跟随的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Particle Mouse Follow</title>
<style>
body {
margin: 0;
overflow: hidden;
background: #000;
}
canvas {
display: block;
}
</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.size = Math.random() * 5 + 1;
this.speedX = Math.random() * 3 - 1.5;
this.speedY = Math.random() * 3 - 1.5;
this.color = `rgba(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255}, 0.7)`;
}
update() {
this.x += this.speedX;
this.y += this.speedY;
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.closePath();
ctx.fill();
}
}
let particles = [];
const mouse = { x: undefined, y: undefined };
window.addEventListener('mousemove', (event) => {
mouse.x = event.x;
mouse.y = event.y;
});
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
function init() {
for (let i = 0; i < 50; i++) {
const x = Math.random() * canvas.width;
const y = Math.random() * canvas.height;
particles.push(new Particle(x, y));
}
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < particles.length; i++) {
particles[i].update();
particles[i].draw();
if (particles[i].size <= 0.3) {
particles.splice(i, 1);
i--;
}
}
requestAnimationFrame(animate);
}
init();
animate();
</script>
</body>
</html>
常见问题及解决方法:
mousemove
事件中及时更新鼠标位置,并且在resize
事件中重新设置画布大小。通过以上方法,可以有效实现并优化JavaScript粒子鼠标跟随效果。
领取专属 10元无门槛券
手把手带您无忧上云