如何用jQuery为SVG feSpecularLighting的点光源坐标添加缓动效果
SVG fePointLight 坐标平滑缓动实现方案
核心限制说明
fePointLight的x/y属于SVG滤镜的原生几何属性,不在CSS可触发过渡动画的属性范围内,因此无法通过transition机制实现属性值变化的缓动效果,所有平滑逻辑需要在JS层通过逐帧值插值实现。
原实现中鼠标移动事件触发时,会直接把计算出的光源坐标赋值给DOM属性,没有中间过渡阶段,因此当鼠标从窗口外快速移入时,坐标差幅度过大就会出现光源瞬间跳转的突兀效果。
具体改造方案
核心逻辑是将「目标光源坐标」和「实际渲染的光源坐标」拆分为两个独立状态,通过逐帧插值让渲染坐标始终平滑追向目标坐标:
- 状态拆分
- 目标光源坐标:由鼠标移动事件实时计算更新,代表光照应该指向的最终位置
- 实际渲染光源坐标:独立存储的当前真正写入DOM的坐标值,初始保持在原默认位置
- 逐帧渲染循环
- 基于
requestAnimationFrame创建持续运行的渲染循环,每一帧通过固定插值系数,让渲染坐标向目标坐标靠近固定比例的距离 - 每帧计算完成后,直接把渲染坐标的值赋值给
fePointLight的x/y属性
- 基于
- 原有逻辑兼容
- 保留原有的鼠标位置计算、窗口尺寸监听的逻辑,仅把原来的直接赋值操作替换为更新目标坐标即可
核心代码改造示例
将原有JS代码替换为以下内容,即可实现平滑缓动效果:
let lightDist = 10000; // 目标光源位置:鼠标移动时实时更新 let targetLightPos = { x: -lightDist, y: -lightDist }; // 实际渲染的光源位置:逐帧向目标值靠近 let renderedLightPos = { x: -lightDist, y: -lightDist }; let currentMousePos = { x: -1, y: -1 }; let windowWidth = $(window).outerWidth(); let windowHeight = $(window).outerHeight(); let ratio = { x: lightDist / (windowWidth / 2), y: lightDist / (windowHeight / 2) }; // 缓动插值系数:可根据需求调整 // 取值范围0.03~0.2,数值越小平滑拖尾效果越强、跟随延迟越高;数值越大响应越跟手、平滑度越低 const easeFactor = 0.08; // 逐帧渲染循环 function updateLightLoop() { // 线性插值计算当前帧的渲染位置 renderedLightPos.x += (targetLightPos.x - renderedLightPos.x) * easeFactor; renderedLightPos.y += (targetLightPos.y - renderedLightPos.y) * easeFactor; // 写入DOM属性 $('fePointLight').attr({ 'x': renderedLightPos.x, 'y': renderedLightPos.y }); requestAnimationFrame(updateLightLoop); } // 启动渲染循环 updateLightLoop(); // 窗口尺寸监听逻辑保留 $(window).on('resize', function() { windowWidth = $(window).outerWidth(); windowHeight = $(window).outerHeight(); ratio = { x: lightDist / (windowWidth / 2), y: lightDist / (windowHeight / 2) }; }); // 鼠标移动监听逻辑保留,仅将原直接赋值替换为更新目标值 $(document).on('mousemove', function(e) { currentMousePos.x = e.pageX; currentMousePos.y = e.pageY; if (currentMousePos.x > (windowWidth / 2)) { targetLightPos.x = ratio.x * (currentMousePos.x - (windowWidth / 2)); } else if (currentMousePos.x < (windowWidth / 2)) { targetLightPos.x = -lightDist + (ratio.x * currentMousePos.x); } if (currentMousePos.y > (windowHeight / 2)) { targetLightPos.y = ratio.y * (currentMousePos.y - (windowHeight / 2)); } else if (currentMousePos.y < (windowHeight / 2)) { targetLightPos.y = -lightDist + (ratio.y * currentMousePos.y); } });
效果说明
- 无论鼠标从窗口哪个位置快速移入,光源都会沿着连续的路径平滑移动到对应位置,不会出现瞬间跳转的突兀感
- 调整
easeFactor的取值,可以在“跟手响应速度”和“平滑柔化效果”之间灵活平衡 - 基于原生
requestAnimationFrame的逐帧更新性能开销极低,不会造成页面动画卡顿
内容的提问来源于stack exchange,提问作者joshmoto
相关产品推荐
相关产品推荐

