js实现流光
流光效果实现方法
流光效果通常指一种动态的光线流动视觉效果,常用于按钮、文字或边框装饰。以下是几种常见的实现方式:
CSS动画实现
使用CSS的linear-gradient和动画可以创建简单的流光效果:
.glow-effect {
background: linear-gradient(90deg, #fff0, #fff, #fff0);
background-size: 200% auto;
animation: shine 2s linear infinite;
}
@keyframes shine {
from { background-position: -200% 0; }
to { background-position: 200% 0; }
}
Canvas实现动态流光
通过Canvas可以实现更复杂的动态流光效果:
const canvas = document.getElementById('glowCanvas');
const ctx = canvas.getContext('2d');
function drawGlow() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
gradient.addColorStop(0, 'rgba(255,255,255,0)');
gradient.addColorStop(0.5, 'rgba(255,255,255,0.8)');
gradient.addColorStop(1, 'rgba(255,255,255,0)');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, canvas.width, canvas.height);
requestAnimationFrame(drawGlow);
}
drawGlow();
SVG实现方案
SVG也可以用来创建流畅的流光效果:
<svg width="300" height="100">
<defs>
<linearGradient id="gradient" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" stop-color="transparent" />
<stop offset="50%" stop-color="white" />
<stop offset="100%" stop-color="transparent" />
</linearGradient>
<mask id="mask">
<rect width="100%" height="100%" fill="url(#gradient)" />
</mask>
</defs>
<rect width="100%" height="100%" fill="blue" mask="url(#mask)" />
<animateTransform
attributeName="gradientTransform"
type="translate"
from="-300 0"
to="300 0"
dur="2s"
repeatCount="indefinite" />
</svg>
WebGL高级流光效果
对于更复杂的3D流光效果,可以使用WebGL:
const gl = canvas.getContext('webgl');
// 初始化WebGL环境
// 创建着色器程序
// 设置流光效果参数
// 在渲染循环中更新流光位置
性能优化建议
- 对于简单效果优先使用CSS实现
- 复杂动画考虑使用Canvas或WebGL
- 使用
requestAnimationFrame代替setInterval - 合理控制动画帧率避免过度消耗资源
以上方法可以根据具体需求选择使用,CSS方案最简单,WebGL方案最灵活但实现难度较高。







