这里有一个有趣的JS小功能 - “会躲避鼠标的粒子“:

<!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>

这个功能的特点:

  1. 生成100个随机颜色的小粒子

  2. 当鼠标靠近时,粒子会像有斥力一样避开

  3. 粒子会缓动回到原位

  4. 粒子碰到窗口边缘会从另一边穿出

  5. 颜色使用HSL模式随机生成,更加鲜艳

  6. 留有拖尾效果,形成动态轨迹

  7. 自动适应窗口大小变化

可以尝试:

  1. 修改particleCount改变粒子数量

  2. 调整force的系数改变排斥力度

  3. 修改hsl颜色参数获得不同的配色方案

  4. 改变半径的随机范围调整粒子大小

这个效果结合了简单的物理模拟和色彩变化,可以作为一个有趣的背景效果,或者作为网页的互动元素

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值