Magnetic Button 磁吸按钮
Buttons slide toward the cursor, but only when it is within 140px, and the pull weakens to zero at the edge. 按钮会朝鼠标滑过去,但只在 140px 范围内,而且越靠边拉力越弱直到归零。
Runs live on this page. Move the pointer, click, or drag — whichever the effect listens for. 就在本页实时运行。移动鼠标、点击或拖拽——看它响应哪一种。
How it works原理拆解
For each button the code measures the distance from its centre to the pointer, then applies translate(dx/d * f, dy/d * f) where f scales from 18 down to 0 across the 140px radius. Normalising by d first is what keeps the movement directional instead of proportional to raw offset. 对每个按钮测量中心到指针的距离,再施加 translate(dx/d * f, dy/d * f),其中 f 在 140px 半径内从 18 衰减到 0。先用 d 归一化,是位移保持「有方向」而不是和绝对偏移成正比的关键。
What to change可以改的地方
- 1Raise the 18 to 30 for a stronger, more toy-like magnet.
- 2Add a rotation of dx/20 degrees so buttons tilt as they are pulled.
- 118 提到 30,磁力会强到像个玩具。
- 2再叠加一个 dx/20 度的旋转,按钮被吸的时候会歪。
Source code源码
Self-contained — paste it into any HTML file and it runs. No libraries. 完全独立——粘进任意 HTML 文件就能跑,不需要任何库。