js实现光圈
实现光圈效果的方法
光圈效果可以通过多种方式实现,以下是几种常见的方法:
使用CSS和JavaScript创建动态光圈
通过CSS定义光圈样式,JavaScript控制动画效果:
// 创建光圈元素
const halo = document.createElement('div');
halo.style.position = 'absolute';
halo.style.width = '100px';
halo.style.height = '100px';
halo.style.borderRadius = '50%';
halo.style.boxShadow = '0 0 20px 10px rgba(255, 255, 255, 0.5)';
halo.style.opacity = '0';
document.body.appendChild(halo);
// 动画控制
function animateHalo(x, y) {
halo.style.left = `${x - 50}px`;
halo.style.top = `${y - 50}px`;
halo.style.opacity = '1';
setTimeout(() => {
halo.style.opacity = '0';
}, 500);
}
// 跟随鼠标移动
document.addEventListener('mousemove', (e) => {
animateHalo(e.clientX, e.clientY);
});
使用Canvas绘制光圈
Canvas提供了更灵活的绘图能力:
const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
function drawHalo(x, y) {
const gradient = ctx.createRadialGradient(x, y, 0, x, y, 50);
gradient.addColorStop(0, 'rgba(255, 255, 255, 0.8)');
gradient.addColorStop(1, 'rgba(255, 255, 255, 0)');
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(x, y, 50, 0, Math.PI * 2);
ctx.fillStyle = gradient;
ctx.fill();
}
document.addEventListener('mousemove', (e) => {
drawHalo(e.clientX, e.clientY);
});
使用WebGL实现高级光圈效果
对于更复杂的光圈效果,可以使用WebGL:
// 初始化WebGL上下文
const canvas = document.createElement('canvas');
const gl = canvas.getContext('webgl');
// 顶点着色器
const vsSource = `
attribute vec2 position;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
}
`;
// 片段着色器
const fsSource = `
precision highp float;
uniform vec2 center;
uniform float time;
void main() {
vec2 uv = gl_FragCoord.xy / vec2(800.0, 600.0);
float dist = distance(uv, center);
float halo = smoothstep(0.2, 0.0, dist);
gl_FragColor = vec4(1.0, 1.0, 1.0, halo * (0.5 + 0.5 * sin(time)));
}
`;
// 编译着色器程序
const shaderProgram = initShaderProgram(gl, vsSource, fsSource);
// 渲染循环
function render(time) {
gl.clear(gl.COLOR_BUFFER_BIT);
// 更新uniforms并绘制
requestAnimationFrame(render);
}
光圈效果的优化技巧
性能优化
对于频繁更新的光圈效果,使用requestAnimationFrame进行动画循环,避免直接操作DOM。Canvas和WebGL版本通常比纯CSS版本性能更好。
视觉效果增强
添加颜色变化、大小变化或透明度动画可以使光圈效果更生动。可以使用GSAP等动画库简化复杂动画的实现。
响应式设计
确保光圈效果在不同屏幕尺寸上正常工作,通过监听resize事件调整Canvas大小或重新计算位置。
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
以上方法可以根据具体需求选择或组合使用,CSS方法最简单但功能有限,Canvas提供了平衡的灵活性和性能,WebGL则适合需要最高性能或最复杂效果的场景。







