背景
最近交流群在讨论一个酷酷的官网
https://labs.lusion.co/,看到里面有一个比较有趣的交互效果,这个鼠标的弹性效果跟IOS的弹性交互有点像,参考这个做了个模拟效果供学习
效果展示
在线Playground: https://stackblitz.com/edit/vitejs-vite-gb3x1qh3?file=src%2Fmain.ts
模拟物理反弹的弹簧阻尼
主要过程
function anim() {
let velocity = [0, 0];
let stiffness = 0.04; // 刚度
let damping = 0.8; // 阻尼
const dx = targetPosition[0] - currentPosition[0];
const dy = targetPosition[1] - currentPosition[1];
velocity[0] += dx * stiffness;
velocity[1] += dy * stiffness;
velocity[0] *= damping;
velocity[1] *= damping;
const maxSpeed = 200; // 限制最大速度
// 计算新的速度并限制在最大速度内
velocity[0] = Math.max(
Math.min(velocity[0] + dx * stiffness, maxSpeed),
-maxSpeed
);
velocity[1] = Math.max(
Math.min(velocity[1] + dy * stiffness, maxSpeed),
-maxSpeed
);
velocity[0] *= damping;
velocity[1] *= damping;
currentPosition[0] += velocity[0];
currentPosition[1] += velocity[1];
setCursorPosition(currentPosition as [number, number]);
requestAnimationFrame(anim);
}