<!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>
效果特点:
-
鼠标移动时生成彩色流光轨迹
-
轨迹点之间用渐变色彩连接
-
轨迹会自动逐渐缩小消失
-
颜色持续循环变化 (HSL色相轮换)
-
带透明拖尾效果
-
自动适应窗口尺寸
可调参数:
-
修改
trails.length > 30
中的数值调整拖尾长度 -
调整
trail.radius *= 0.95
系数改变消失速度 -
修改
hue += 2
改变颜色变化速度 -
调整初始
radius
值改变线条粗细
这个效果看起来像鼠标拖着一条会呼吸的霓虹灯带,适合作为网页的动态背景或光标特效。可以通过修改颜色算法(比如改用RGB)创造不同的视觉效果!