一段精簡的 HTML5 Canvas 代碼,即可生成滑鼠跟隨、色彩綻放的動態粒子系統。核心邏輯:監聽 mousemove,在滑鼠位置生成粒子,每幀更新位置、透明度並重繪,利用 globalCompositeOperation = 'lighter' 實現光疊加效果。
<canvas id="myCanvas"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
ctx.lineWidth = 0.2;
ctx.lineCap = 'round';
ctx.globalCompositeOperation = 'lighter';
let particles = [];
canvas.onmousemove = e => {
particles.push({x: e.clientX, y: e.clientY, hue: Math.random()*360, life: 1});
};
function animate() {
ctx.fillStyle = 'rgba(0,0,0,0.1)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
particles = particles.filter(p => {
ctx.beginPath();
ctx.arc(p.x, p.y, 2, 0, Math.PI*2);
ctx.strokeStyle = `hsla(${p.hue}, 100%, 50%, ${p.life})`;
ctx.stroke();
p.life -= 0.01;
return p.life > 0;
});
requestAnimationFrame(animate);
}
animate();
</script>
lighter 模式讓重疊粒子亮度疊加,營造發光感resize 事件同步調整尺寸此特效可作為頁面背景、載入動畫或互動裝置,代碼量極小卻視覺張力十足。