鼠标牵引的流光线条

<!DOCTYPE html>
<html>
<body style="background: #000; margin: 0; overflow: hidden">
<canvas id="canvas"></canvas>

<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

// 轨迹点数组
const trails = [];
let hue = 0; // 色相值(用于颜色变化)

class Trail {
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.hue = hue; // 存储当前颜色
        this.radius = 5; // 初始半径
    }
}

// 鼠标移动监听
window.addEventListener('mousemove', (e) => {
    // 添加新的轨迹点
    trails.push(new Trail(e.clientX, e.clientY));
    // 保持轨迹长度不超过30个点
    if (trails.length > 30) trails.shift();
});

// 动态绘制
function animate() {
    ctx.fillStyle = 'rgba(0, 0, 0, 0.05)';
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // 循环处理每个轨迹点
    trails.forEach((trail, index) => {
        const next = trails[index + 1];
        if (next) {
            // 创建渐变连线
            const gradient = ctx.createLinearGradient(
                trail.x, trail.y, next.x, next.y
            );
            gradient.addColorStop(0, `hsl(${trail.hue}, 100%, 50%)`);
            gradient.addColorStop(1, `hsl(${next.hue}, 100%, 50%)`);

            // 绘制连线
            ctx.beginPath();
            ctx.lineWidth = trail.radius;
            ctx.strokeStyle = gradient;
            ctx.moveTo(trail.x, trail.y);
            ctx.lineTo(next.x, next.y);
            ctx.stroke();
        }

        // 动态变化属性
        trail.radius *= 0.95; // 逐渐缩小
        trail.hue += 2; // 颜色渐变
    });

    // 颜色循环
    hue = (hue + 1) % 360;
    requestAnimationFrame(animate);
}

animate();

// 窗口大小变化处理
window.addEventListener('resize', () => {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
});
</script>
</body>
</html>

效果特点

  1. 鼠标移动时生成彩色流光轨迹

  2. 轨迹点之间用渐变色彩连接

  3. 轨迹会自动逐渐缩小消失

  4. 颜色持续循环变化 (HSL色相轮换)

  5. 带透明拖尾效果

  6. 自动适应窗口尺寸

可调参数

  • 修改 trails.length > 30 中的数值调整拖尾长度

  • 调整 trail.radius *= 0.95 系数改变消失速度

  • 修改 hue += 2 改变颜色变化速度

  • 调整初始 radius 值改变线条粗细

这个效果看起来像鼠标拖着一条会呼吸的霓虹灯带,适合作为网页的动态背景或光标特效。可以通过修改颜色算法(比如改用RGB)创造不同的视觉效果!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值