js实现阻尼
阻尼效果的实现方法
阻尼效果常用于实现平滑滚动或缓动动画,以下是几种常见的实现方式:

使用requestAnimationFrame实现基础阻尼
function dampenAnimation(target, current, velocity, damping, deltaTime) {
const difference = target - current;
velocity += difference * deltaTime;
velocity *= damping;
return current + velocity;
}
let position = 0;
let velocity = 0;
const target = 100;
const damping = 0.8;
function animate() {
position = dampenAnimation(target, position, velocity, damping, 0.016);
console.log(position);
if (Math.abs(position - target) > 0.1) {
requestAnimationFrame(animate);
}
}
animate();
滚动阻尼效果
为网页滚动添加阻尼效果:

let startY = 0;
let currentY = 0;
let targetY = 0;
let velocity = 0;
const damping = 0.2;
document.addEventListener('wheel', (e) => {
e.preventDefault();
targetY += e.deltaY;
});
function animateScroll() {
const diff = targetY - currentY;
velocity += diff * 0.1;
velocity *= damping;
currentY += velocity;
window.scrollTo(0, currentY);
requestAnimationFrame(animateScroll);
}
animateScroll();
物理引擎式阻尼
更接近真实物理的阻尼实现:
class Dampener {
constructor(mass = 1, damping = 0.5, stiffness = 100) {
this.mass = mass;
this.damping = damping;
this.stiffness = stiffness;
this.position = 0;
this.velocity = 0;
}
update(target, deltaTime) {
const springForce = -this.stiffness * (this.position - target);
const dampingForce = -this.damping * this.velocity;
const acceleration = (springForce + dampingForce) / this.mass;
this.velocity += acceleration * deltaTime;
this.position += this.velocity * deltaTime;
return this.position;
}
}
应用阻尼到DOM元素
为DOM元素移动添加阻尼效果:
const element = document.getElementById('box');
const dampener = new Dampener();
function moveTo(x, y) {
const deltaTime = 0.016; // 约60fps
const currentX = dampener.update(x, deltaTime);
const currentY = dampener.update(y, deltaTime);
element.style.transform = `translate(${currentX}px, ${currentY}px)`;
if (Math.abs(dampener.velocity) > 0.01) {
requestAnimationFrame(() => moveTo(x, y));
}
}
moveTo(200, 200);
参数调整建议
- 增大damping值会更快停止运动
- 减小stiffness会使运动更柔软
- mass影响运动的惯性效果
- deltaTime应接近实际帧间隔时间
这些实现可以根据具体需求调整参数,适用于滚动效果、动画过渡或物理模拟等场景。






