<!DOCTYPE html>
<html>
<body style="background: #000; margin: 0">
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 设置canvas全屏
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 创建粒子数组
const particles = [];
const particleCount = 100;
// 粒子构造函数
function Particle() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.vx = 0;
this.vy = 0;
this.radius = Math.random() * 3 + 1;
this.color = `hsl(${Math.random() * 360}, 50%, 50%)`;
}
// 生成粒子
for (let i = 0; i < particleCount; i++) {
particles.push(new Particle());
}
// 鼠标坐标
let mouse = { x: null, y: null };
window.addEventListener('mousemove', (e) => {
mouse.x = e.x;
mouse.y = e.y;
});
// 动画循环
function animate() {
ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
particles.forEach(particle => {
// 计算粒子与鼠标的距离
const dx = mouse.x - particle.x;
const dy = mouse.y - particle.y;
const distance = Math.sqrt(dx * dx + dy * dy);
// 当距离小于100像素时施加排斥力
if (distance < 100) {
const force = (100 - distance) / 50;
const angle = Math.atan2(dy, dx);
particle.vx -= force * Math.cos(angle);
particle.vy -= force * Math.sin(angle);
}
// 应用缓动和边界限制
particle.x += particle.vx;
particle.y += particle.vy;
particle.vx *= 0.95;
particle.vy *= 0.95;
// 边界检测
if (particle.x < 0) particle.x = canvas.width;
if (particle.x > canvas.width) particle.x = 0;
if (particle.y < 0) particle.y = canvas.height;
if (particle.y > canvas.height) particle.y = 0;
// 绘制粒子
ctx.beginPath();
ctx.arc(particle.x, particle.y, particle.radius, 0, Math.PI * 2);
ctx.fillStyle = particle.color;
ctx.fill();
});
requestAnimationFrame(animate);
}
animate();
// 窗口大小变化时重置canvas尺寸
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
</script>
</body>
</html>
这个功能的特点:
-
生成100个随机颜色的小粒子
-
当鼠标靠近时,粒子会像有斥力一样避开
-
粒子会缓动回到原位
-
粒子碰到窗口边缘会从另一边穿出
-
颜色使用HSL模式随机生成,更加鲜艳
-
留有拖尾效果,形成动态轨迹
-
自动适应窗口大小变化
可以尝试:
-
修改particleCount改变粒子数量
-
调整force的系数改变排斥力度
-
修改hsl颜色参数获得不同的配色方案
-
改变半径的随机范围调整粒子大小
这个效果结合了简单的物理模拟和色彩变化,可以作为一个有趣的背景效果,或者作为网页的互动元素