js運動是我們學習js必不可少的研究部分,首先我們要知道js的運動其實僅僅是不斷改變元素的某個屬性值而已,比如不斷改變一個絕對定位div的left值,那么你看到的效果就是這個div不斷的向右邊運動,那么運動的原理就是這樣。
我們知道從a這一點到b這一點我們的運動方式有很多,
1.比如勻速運動到這一點
2.比如先快后慢,
3.必須先慢后快等等
所以我們的運動算法也有很多,那么下面我就圖解一下如何寫我們自己的運動算法
先看勻速算法

於是我們可以用js寫出這段代碼
/** 運動算法 * t:動畫已經消耗的時間 * b:小球初始位置 * c:小球的需要移動額距離 * 動畫持續的總時間 * */ var tween = { linear: function(t, b, c, d){ return c * t / d + b; } }
然后我們看看非勻速運動

我們用代碼寫出來
var tween = {
strongEaseOut:function( t, b, c, d){
return t * t *c / (d *d) + b;
},
}
我們現在只是介紹兩種不同的運動算法,當然運動算法還要很多,我們不意義例舉,我們接着看如何寫改變屬性的js
首先我們定義一個運動類
var Animate = function ( dom ) {
this.dom = dom;
this.startTime = 0;
this.startPos = 0;
this.endPos = 0;
this.propertyName = null;
this.easing = null;
this.duration = null;
}
主要是初始化一些數據,然后我們在Animate的原型上定義一個start方法,該方法表示運動開始
Animate.prototype.start = function ( propertyName,endPos,duration,easing ){
this.startTime = +new Date;//記錄現在的開始時間
this.startPos = this.dom.getBoundingClientRect()[ propertyName ];//記錄開始的位置
this.propertyName = propertyName;//需要改變的屬性(傳)
this.endPos = endPos;//得到目標位置(傳)
this.duration = duration;//得到需要的時間(傳)
this.easing = tween[ easing ]//選擇哪種運動的算法(傳)
var self = this;
var timeId = setInterval(function(){
//如果self返回false,則取消定時器
if( self.step()=== false ) {
clearInterval( timeId )
}
},19)
}
上面的setInterval每隔19毫秒就會執行一次,每次都是執行step方法,step方法就是每次需要計算更新小球的位置
Animate.prototype.step = function(){
//目前的時間
var t = +new Date;
//如果時間超過開始時間和需要時間之和,則矯正目前的位置為目標位置
if( t >= this.startTime + this.duration ) {
this.update( this.endPos )
return false;//返回false為了取消定時器
}
//計算小球的位置
var pos = this.easing( t - this.startTime, this.startPos, this.endPos-this.startPos ,this.duration)
//更新div的屬性
this.update( pos )
}
那么update方法也僅僅就是更新div的屬性而已
//更新當前位置
Animate.prototype.update = function( pos ){
this.dom.style[ this.propertyName ] = pos + 'px'
}
接下來我們看看我們在html里面如何執行,html代碼
<div style="position: absolute;background: blue;width: 100px;height: 100px;left: 0;" id="div"></div>
然后是執行代碼
var div = document.getElementById('div')
var animate = new Animate( div )
animate.start('left',500,5000,'linear')
到現在我們整個運動就結束了
完整的代碼地址在我的github上https://github.com/jiangzhenfei/Animate/blob/master/index.html
