今天我们来模拟animate动画库实现几个动画效果;
首先,在html文件创建一个div元素作为运动物体吧☺️
其次,在css文件里写几个简单样式吧☺️
#move {
position: absolute;
width: 30px;
height: 30px;
border-radius: 100%;
background-color: red;
}
接下来,主要的运动逻辑就在js文件里实现啦
- 创建一个用于实现几种动画效果的tween对象
/*
定义的tween内的动画效果属性都为缓动算法,他们都接受以下 4 个参数。
t:动画已消耗的时间。
b: 小球原始位置。
c: 小球目标位置。
d: 动画持续的总时间。
返回的值则是动画元素应该处在的当前位置
*/
var tween = {
linear: function( t, b, c, d ){
return c*t/d + b;
},
easeIn: function( t, b, c, d ){
return c * ( t /= d ) * t + b;
},
strongEaseIn: function(t, b, c, d){
return c * ( t /= d ) * t * t * t * t + b;
},
strongEaseOut: function(t, b, c, d){
return c * ( ( t = t / d - 1) * t * t * t * t + 1 ) + b;
},
sineaseIn: function( t, b, c, d ){
return c * ( t /= d) * t * t + b;
},
sineaseOut: function(t,b,c,d){
return c * ( ( t = t / d - 1) * t * t + 1 ) + b;
}
};
- 定义Animate动画类
// 定义Animate类
var Animate = function( dom ){
this.dom = dom; // 进行运动的 dom 节点
this.startTime = 0; // 动画开始时间
this.startPos = 0; // 动画开始时,dom 节点的位置,即 dom 的初始位置
this.endPos = 0; // 动画结束时,dom 节点的位置,即 dom 的目标位置
this.propertyName = null; // dom 节点需要被改变的 css 属性名
this.easing = null; // 缓动算法
this.duration = null; // 动画持续时间
};
- 定义启动动画函数
/*
启动动画函数
Animate.prototype.start 方法接受以下 4 个参数。
propertyName:要改变的 CSS 属性名,比如'left'、'top',分别表示左右移动和上下移动。
endPos: 小球运动的目标位置。
duration: 动画持续时间。
easing: 缓动算法。
*/
Animate.prototype.start = function( propertyName, endPos, duration, easing ){
this.startTime = +new Date; // 动画启动时间
this.startPos = this.dom.getBoundingClientRect()[ propertyName ]; // dom 节点初始位置
this.propertyName = propertyName; // dom 节点需要被改变的 CSS 属性名
this.endPos = endPos; // dom 节点目标位置
this.duration = duration; // 动画持续事件
this.easing = tween[ easing ]; // 缓动算法
var self = this;
var timeId = setInterval(function(){ // 启动定时器,开始执行动画
if ( self.step() === false ){ // 如果动画已结束,则清除定时器
clearInterval( timeId );
}
}, 19 );
};
- 定义每一步需要做的运动
// 每一步运动要做的事
Animate.prototype.step = function(){
var t = +new Date; // 取得当前时间
if ( t >= this.startTime + this.duration ){ // 当前时间>起始时间+持续时间时,停止运动
this.update( this.endPos ); // 更新小球的 CSS 属性值
return false;
}
var pos = this.easing( t - this.startTime, this.startPos, this.endPos - this.startPos, this.duration );
// pos 为小球当前位置
this.update( pos ); // 更新小球的 CSS 属性值
};
- 通过改变css属性更新运动物体的位置
// 更新运动物体 CSS 属性值
Animate.prototype.update = function( pos ){
this.dom.style[ this.propertyName ] = pos + 'px';
};
大功告成,下面可以验证运动效果啦😆
// 测试运动效果:
var moveEle = document.getElementById( 'move' );
var animate = new Animate( moveEle );
animate.start( 'left', 500, 1000, 'strongEaseOut' ); // 从左到右的运动
// animate.start( 'top', 1500, 500, 'strongEaseIn' ); // 从上到下的运动