浮动动画

let bobberPhase = 0;
const bobberAnimate = () => {
if (!mini || !bobber.parentNode) return; // 已移除则停止
bobberPhase = (bobberPhase + 0.05) % (Math.PI * 2);
const offsetY = Math.sin(bobberPhase) * 15; // -15px ~ +15px
bobber.style.transform …


This content originally appeared on DEV Community and was authored by NikiMunger

let bobberPhase = 0;
const bobberAnimate = () => {
  if (!mini || !bobber.parentNode) return;  // 已移除则停止
  bobberPhase = (bobberPhase + 0.05) % (Math.PI * 2);
  const offsetY = Math.sin(bobberPhase) * 15;  // -15px ~ +15px
  bobber.style.transform = `translateX(-50%) translateY(${offsetY}px)`;
  requestAnimationFrame(bobberAnimate); 
};
bobberAnimate();  // 启动

sin()永远在-1~1之间
所以offsetY永远在-15px ~ 15px之间
所以bobber永远在-15px ~ 15px之间上下浮动

% (Math.PI * 2)

  • 2π 是正弦波的一个周期,
    所以只需要让相位保持在:0 ~ 2π这一圈就够了。

  • 不取模会导致 bobberPhase 无限变大

  • 让动画永远平滑地循环
    % (2π) 的作用:bobberPhase += 0.05,如果超过 2π,就从 0 重新开始
    这样你就得到一个永远循环的波:0 → 0.05 → 0.10 → ... → 6.28 → 0 → 0.05 → 0.10 → ...相位永远不会失控,也不会变成巨大数字。


This content originally appeared on DEV Community and was authored by NikiMunger


Print Share Comment Cite Upload Translate Updates
APA

NikiMunger | Sciencx (2025-11-19T02:44:35+00:00) 浮动动画. Retrieved from https://www.scien.cx/2025/11/19/%e6%b5%ae%e5%8a%a8%e5%8a%a8%e7%94%bb/

MLA
" » 浮动动画." NikiMunger | Sciencx - Wednesday November 19, 2025, https://www.scien.cx/2025/11/19/%e6%b5%ae%e5%8a%a8%e5%8a%a8%e7%94%bb/
HARVARD
NikiMunger | Sciencx Wednesday November 19, 2025 » 浮动动画., viewed ,<https://www.scien.cx/2025/11/19/%e6%b5%ae%e5%8a%a8%e5%8a%a8%e7%94%bb/>
VANCOUVER
NikiMunger | Sciencx - » 浮动动画. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/11/19/%e6%b5%ae%e5%8a%a8%e5%8a%a8%e7%94%bb/
CHICAGO
" » 浮动动画." NikiMunger | Sciencx - Accessed . https://www.scien.cx/2025/11/19/%e6%b5%ae%e5%8a%a8%e5%8a%a8%e7%94%bb/
IEEE
" » 浮动动画." NikiMunger | Sciencx [Online]. Available: https://www.scien.cx/2025/11/19/%e6%b5%ae%e5%8a%a8%e5%8a%a8%e7%94%bb/. [Accessed: ]
rf:citation
» 浮动动画 | NikiMunger | Sciencx | https://www.scien.cx/2025/11/19/%e6%b5%ae%e5%8a%a8%e5%8a%a8%e7%94%bb/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.