JavaScript 动态粒子鼠标吸附是一种常见的网页交互效果,它通过在页面上创建一系列的粒子(通常是圆形),并使这些粒子在鼠标移动时跟随鼠标指针,产生一种吸附的效果。这种效果通常用于增强用户体验,使网页看起来更加生动和有趣。
以下是一个简单的JavaScript和HTML5 Canvas实现的动态粒子鼠标吸附效果的示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Particle Mouse Attraction</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.size = Math.random() * 5 + 1;
this.speedX = Math.random() * 3 - 1.5;
this.speedY = Math.random() * 3 - 1.5;
}
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 maxDistance = 100;
let force = (maxDistance - distance) / maxDistance;
let directionX = forceDirectionX * force * 10;
let directionY = forceDirectionY * force * 10;
if (distance < maxDistance) {
this.x -= directionX;
this.y -= directionY;
}
this.x += this.speedX;
this.y += this.speedY;
if (this.size > 0.2) this.size -= 0.1;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fillStyle = '#fff';
ctx.fill();
}
}
let particles = [];
let mouse = { x: undefined, y: undefined };
window.addEventListener('mousemove', function(event) {
mouse.x = event.x;
mouse.y = event.y;
});
window.addEventListener('resize', function() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
function init() {
for (let i = 0; i < 50; i++) {
let x = Math.random() * canvas.width;
let 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(mouse);
particles[i].draw();
if (particles[i].size <= 0.3) {
particles.splice(i, 1);
i--;
}
}
requestAnimationFrame(animate);
}
init();
animate();
</script>
</body>
</html>
问题:粒子效果在某些设备上运行缓慢或不流畅。
原因:可能是由于粒子数量过多,或者动画帧率过高导致的性能问题。
解决方法:
requestAnimationFrame
来优化动画性能。通过上述方法,可以有效地解决粒子效果在不同设备上的性能问题,确保用户体验的一致性。
领取专属 10元无门槛券
手把手带您无忧上云