js实现阻尼


阻尼效果的实现方法
阻尼效果常用于模拟物理运动中的阻力,使动画或交互更自然。以下是几种常见实现方式:
使用缓动函数
function damp(current, target, dampingFactor) {
return current + (target - current) * dampingFactor;
}
// 使用示例
let position = 0;
const target = 100;
const damping = 0.1;
function update() {
position = damp(position, target, damping);
requestAnimationFrame(update);
}
基于速度的阻尼
let position = 0;
let velocity = 0;
const target = 100;
const damping = 0.1;
const stiffness = 0.2;
function update() {
const distance = target - position;
const acceleration = distance * stiffness - velocity * damping;
velocity += acceleration;
position += velocity;
requestAnimationFrame(update);
}
使用时间衰减
function dampOverTime(value, target, damping, deltaTime) {
return value + (target - value) * (1 - Math.exp(-damping * deltaTime));
}
实际应用案例(滚动阻尼)
let scrollPosition = 0;
let targetScroll = 0;
let velocity = 0;
const damping = 0.3;
const stiffness = 0.5;
window.addEventListener('wheel', (e) => {
targetScroll += e.deltaY;
e.preventDefault();
});
function animate() {
const distance = targetScroll - scrollPosition;
const acceleration = distance * stiffness - velocity * damping;
velocity += acceleration;
scrollPosition += velocity;
window.scrollTo(0, scrollPosition);
requestAnimationFrame(animate);
}
animate();
参数调节建议
- 阻尼系数通常在0.1-0.3之间
- 刚度系数通常在0.2-0.5之间
- 时间步长应使用requestAnimationFrame的deltaTime
这些实现可以根据具体需求进行调整,阻尼效果的质量取决于参数的精细调节。






