js实现减速
实现减速效果的JavaScript方法
使用缓动函数(Easing Function)
缓动函数可以模拟自然减速效果。以下是一个二次缓动函数的实现示例:
function easeOutQuad(t, b, c, d) {
t /= d;
return -c * t*(t-2) + b;
}
let start = 0;
const end = 100;
const duration = 1000; // 毫秒
const startTime = Date.now();
function animate() {
const elapsed = Date.now() - startTime;
const value = easeOutQuad(elapsed, start, end, duration);
if (elapsed < duration) {
console.log(value);
requestAnimationFrame(animate);
} else {
console.log(end);
}
}
animate();
基于速度的减速
通过逐渐减小速度值来实现减速:
let position = 0;
let velocity = 10;
const friction = 0.95;
function update() {
velocity *= friction;
position += velocity;
if (Math.abs(velocity) > 0.1) {
console.log(position);
requestAnimationFrame(update);
}
}
update();
CSS transition配合JavaScript
结合CSS的transition-timing-function实现减速效果:
const element = document.getElementById('box');
element.style.transition = 'all 2s ease-out';
element.style.transform = 'translateX(200px)';
使用Web动画API
现代浏览器支持的Web动画API可以方便地创建减速动画:
const element = document.getElementById('box');
element.animate([
{ transform: 'translateX(0)' },
{ transform: 'translateX(200px)' }
], {
duration: 1000,
easing: 'ease-out'
});
物理引擎模拟
对于更复杂的减速效果,可以使用物理引擎库如matter.js:
const engine = Matter.Engine.create();
const box = Matter.Bodies.rectangle(100, 100, 80, 80, {
friction: 0.05
});
Matter.Engine.update(engine, (delta) => {
console.log(box.position);
});
选择哪种方法取决于具体需求场景。简单的UI动画可以使用CSS或Web动画API,游戏开发可能需要基于速度的物理模拟,而复杂的交互效果可能需要缓动函数。







