js easing实现
缓动函数实现原理
缓动函数(Easing Functions)通过修改动画的进度比例(t,范围0-1),实现非匀速运动效果。核心是数学公式对t的变换,常见类型包括线性、二次、弹性等。
基础缓动函数示例
以下为JavaScript实现的经典缓动函数,输入输出均为0-1范围内的值:
线性缓动(无变化)

function linear(t) {
return t;
}
二次缓动(加速/减速)
function easeInQuad(t) {
return t * t;
}
function easeOutQuad(t) {
return 1 - (1 - t) * (1 - t);
}
function easeInOutQuad(t) {
return t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2;
}
弹性缓动(带回弹效果)

function easeOutElastic(t) {
const c4 = (2 * Math.PI) / 3;
return t === 0 ? 0 :
t === 1 ? 1 :
Math.pow(2, -10 * t) * Math.sin((t * 10 - 0.75) * c4) + 1;
}
应用缓动函数到动画
通过缓动函数修改动画的progress值,再应用于实际属性变化:
function animate(element, duration, easingFn, property, start, end) {
let startTime = null;
function step(timestamp) {
if (!startTime) startTime = timestamp;
const elapsed = timestamp - startTime;
const progress = Math.min(elapsed / duration, 1);
const easedProgress = easingFn(progress); // 应用缓动
const currentValue = start + (end - start) * easedProgress;
element.style[property] = `${currentValue}px`;
if (progress < 1) {
requestAnimationFrame(step);
}
}
requestAnimationFrame(step);
}
// 示例:使用二次缓动移动元素
const box = document.getElementById('box');
animate(box, 1000, easeInOutQuad, 'left', 0, 200);
扩展缓动类型
-
三次贝塞尔曲线
通过cubic-bezier()生成自定义缓动曲线,CSS原生支持:transition: all 0.5s cubic-bezier(0.68, -0.6, 0.32, 1.6); -
阶跃函数
使用steps()实现分帧动画效果:function easeSteps(t, steps) { return Math.floor(t * steps) / steps; }
性能优化建议
- 优先使用CSS缓动(如
transition-timing-function),性能优于JavaScript。 - 复杂动画考虑使用GSAP等库,内置优化过的缓动函数。






