首頁 > web前端 > js教程 > 主體

javascript動畫淺析_javascript技巧

WBOY
發布: 2016-05-16 17:50:29
原創
1025 人瀏覽過
動畫原理

所謂的動畫,就是透過一些列的運動形成的動的畫面。在網頁中,我們可以透過不斷的改變元素的css值,來達到動的效果。

用到的公式

總距離S = 總時間T * 速度V 即: V = S/T
當前距離s = S/T * 已耗時t 即: s = S * (t/T)
即:當前距離= 總距離* (已耗時/總時間)
即:動畫元素開始值(動畫元素結束值- 動畫元素開始值) * (目前時間-開始時間) / (動畫需要時間) 值的格式

有了上面這些公式,我們就能利用javascript的setInterval或者setTimeout來做一個簡單的動畫了。
然而想要做一個動畫庫,就不得不考慮另外一些因素了。 例如同一個元素的動畫,就必須要有順序的執行。不同元素的動畫可以同步運作。

如此一來,就必須得用另外一個物件來管理這些動畫了。我開始的想法是說每個元素都放在一個陣列裡,用幾個setInterval來循環取出數組中的動畫函數依序執行。

animate1 = [{elem,fn},{elem,fn}];
animate2 = [{elem,fn},{elem,fn}];

這樣就能達到,相同的元素動畫,是有順序的執行,而不同的則可以同時運行了。然後這樣卻有一個問題,那就是如果超過10個元素的動畫。程式就要開十個setInterval。

為了避免這樣的情況發生,就在上面的基礎上做了一些改進。使得,不論多少個動畫。都使用一個setInterval來完成。修改後結構如下。

複製程式碼 程式碼如下:

[
[ ,fn,fn,fn]],
[elem,[fn,fn,fn,fn]],
[elem,[fn,fn,fn,fn]]
]


這樣一來,就可以用一個setInterval來完成所有動畫了。 所需要做就是,循環取出elem,並執行elem後面一個元素的頭一個fn,fn執行完畢後刪除fn。呼叫下一個fn,如果fn全部為空則從大的數組中刪除elem,如果elem為空時,則清楚setInterval。這樣一來,邏輯上便可以走得通了。

然而動畫最關鍵的因素還有一個,那就是緩動。 如果沒有緩動,那麼動畫效果看起來就非常的僵硬。千篇一律。目前做js動畫用到的緩動演算法是很多的,大致分為兩類。
一種是fla​​sh類,一種是prototype類。

flash的需要四個參數。分別是,
1.時間初始話的時間t
2.動畫的初始值b
3.動畫的結束值c
4.動畫持續的時間d
下面是一個flash 類別的等速運動演算法
Linear: function(t,b,c,d){ return c*t/d b; }
另一種則是prototype,這一類的參數只需要一個,那就是當前時間t與持續時間d的比值(t/d)
我採用了第二種,因為它的參數方便。也更適合上面的動畫公式,下面是一個prototype類的勻速運動演算法
linear : function(t){ return t;}.
加入緩動後上面的公式變為
動畫元素開始值(動畫元素結束值- 動畫元素開始值) * 緩動函數((當前時間-開始時間) / (動畫需要時間)) 值的格式。
至此便是整個動畫類設計便結束了。其中參考了一些其它人的博客,在此表示感謝!
最後,還是貼一下詳細代碼吧。
複製程式碼 程式碼如下:

/**
* 作成時刻 2012/08/29
* @author lynx cat.
* @バージョン 0.77ベータ。
*/

(function(win,doc){
var win = win || window;
var doc = doc || win. document,
pow = Math.pow,
sin = Math.sin,
PI = Math.PI,
BACK_CONST = 1.70158;
var Easing = {
// 匀速运動
linear : function(t){
return t;
},
easeIn : function (t) {
return t * t;
},
easeOut : function (t) {
return ( 2 - t) * t;
},
ease Both : function (t) {
return (t *= 2)
.5 * t * t :
.5 * (1 - (--t) * (t - 2));
},
easeInStrong : function (t) {
return t * t * t * t;
},
easeOutStrong : function (t) {
return 1 - (--t) * t * t * t;
ease BothStrong: function (t ) {
return (t *= 2)
.5 * t * t * t :
.5 * (2 - (t -= 2) * t * t * t);
},
easeOutQuart : function(t){
return -(pow((t-1), 4) -1)
},
easeInOutExpo : function(t ){
if(t===0) 戻り値 0;
if(t===1) 戻り値 1;
if((t/=0.5) return 0.5 * (-pow(2, -10 * --t) 2);
easeOutExpo : function(t){
return (t===1) ? 1 : -pow(2, -10 * t) 1;
},
swingFrom : function(t) {
return t*t*((BACK_CONST 1)*t - BACK_CONST);
},
swingTo: function(t) {
return (t-=1)*t*((BACK_CONST 1)*t BACK_CONST) 1;
},
正弦波 : function(t) {
return (-Math.cos(t*PI)/2) 0.5;
},
フリッカー : function(t) {
var t = t (Math.random()-0.5)/5;
return this.sinusoidal(t 1 ? 1 : t);
},
backIn : function (t) {
if (t === 1) t -= .001;
return t * t * ((BACK_CONST 1) * t - BACK_CONST);
},
backOut : function (t) {
return (t -= 1) * t * ((BACK_CONST 1) * t BACK_CONST) 1;
},
bounce : function (t) {
var s = 7.5625, r;
if (t r = s * t * t;
}
else if (t r = s * (t -= (1.5 / 2.75)) * t .75;
}
else if (t r = s * (t -= (2.25 / 2.75)) * t .9375;
}
else {
r = s * (t -= (2.625 / 2.75)) * t .984375;
}
r を返します。
}
};
/**
* 会話メソッドを含むオブジェクトを返すために使用されるコーナーストーン
* @param elem
* @return {Object}
*/
function catfx(elem){
elem = typeof elem === 'string' ? doc.getElementById(elem) : 要素;
新しい fx(elem) を返します;
}
/**
* 会話メソッドを含むオブジェクトを返すために使用される内部コーナーストーン
* @param elem
* @return {Object}
*/
function fx(elem){
this.elem = elem;
これを返します;
}
/**
* 基本クラスには、いくつかの基本的なメソッドと不変式が含まれています
*/
var fxBase = {
速度 : {
遅い : 600、
速い : 200、
デフォルト : 400
},
fxAttrs : [],
fxMap:[],
/**
* オブジェクト要素の CSS 値を返します
* @param elem
* @param p
* @return css value
*/
getStyle : function(){
var fn = function (){} ;
if('getComputedStyle' in win){
fn = function(elem, p){
var p = p.replace(/-(w)/g,function(i,str){
return str.toUpperCase()
});
var val = getComputedStyle(elem, null)[p];
if(~(' ' p ' ').indexOf(' 左、右、上、下 ') && val === 'auto'){
val = '0px';
}
値を返します。
}
}else {
fn = function(elem, p){
var p = p.replace(/-(w)/g,function(i,str){
str.toUpperCase() を返します
});
var val = elem.currentStyle[p];
if(~(' ' p ' ').indexOf(' width height') && val === 'auto'){
var rect = elem.getBoundingClientRect();
val = ( p === 'width' ? rect.right - rect.left : rect.bottom - rect.top ) 'px';
}
if(p === 'opacity'){
var filter = elem.currentStyle.filter;
if( /opacity/.test(filter) ){
val = filter.match( /d / )[0] / 100;
val = (val === 1 || val === 0) ? val.toFixed(0) : val.toFixed(1);
}else if( val === 未定義 ){
val = 1;
}
}
if(~(' ' p ' ').indexOf(' 左、右、上、下 ') && val === 'auto'){
val = '0px';
}
値を返します。
}
}
return fn;
}(),
/**
* オブジェクト要素の CSS 値を返します
* @param カラー値 (赤、ピンク、青、その他の英語はまだサポートされていません)
* @return rgb(x,x,x)
*/
getColor : function(val){
var r, g, b;
if(/rgb/.test(val)){
var arr = val.match(/d /g);
r = arr[0];
g = arr[1];
b = arr[2];
}else if(/#/.test(val)){
var len = val.length;
if( len === 7 ){
r = parseInt( val.slice(1, 3), 16);
g = parseInt( val.slice(3, 5), 16);
b = parseInt( val.slice(5), 16);
}
else if( len === 4 ){
r = parseInt(val.charAt(1) val.charAt(1), 16);
g = parseInt(val.charAt(2) val.charAt(2), 16);
b = parseInt(val.charAt(3) val.charAt(3), 16);
}
}else{
戻り値;
}
return {
r : parseFloat(r),
g : parseFloat(g),
b : parseFloat(b)
}
},
/**
* Return the parsed css
* @param prop
* @return {val:val,unit:unit}
*/
parseStyle : function(prop){
var val = parseFloat(prop),
unit = prop.replace(/^[-d.] /, '');
if(isNaN(val)){
val = this.getColor(unit);
unit = '';
}
return {val : val, unit : unit};
},
/**
* Set the transparency of the element
* @param elem
* @param val
*/
setOpacity : function(elem, val){
if( 'getComputedStyle' in win ){
elem.style.opacity = val === 1 ? '' : val;
}else{
elem.style.zoom = 1;
elem.style.filter = val === 1 ? '' : 'alpha(opacity=' val * 100 ')';
}
},
/**
* Set the css value of the element
* @param elem
* @param prop
* @param val
*/
setStyle : function(elem, prop, val){
if(prop != 'opacity'){
prop = prop.replace(/-(w)/g,function(i,p){
return p.toUpperCase();
});
elem.style[prop] = val;
}else{
this.setOpacity(elem, val);
}
},
/**
* Return the parsed prop
* @param prop
* @return {prop}
*/
parseProp : function(prop){
var props = {};
for(var i in prop){
props[i] = this.parseStyle(prop[i].toString());
}
return props;
},
/**
* Correct user parameters
* @param elem
* @param duration
* @param easing
* @param callback
* @return {options}
*/
setOption : function(elem,duration, easing, callback){
var options = {};
var _this = this;
options.duration = function(duration){
if(typeof duration == 'number'){
return duration;
}else if(typeof duration == 'string' && _this.speed[duration]){
return _this.speed[duration];
}else{
return _this.speed.defaults;
}
}(duration);
options.easing = function(easing){
if(typeof easing == 'function'){
return easing;
}else if(typeof easing == 'string' && Easing[easing]){
return Easing[easing];
}else{
return Easing.linear;
}
}(easing);
options.callback = function(callback){
var _this = this;
return function (){
if(typeof callback == 'function'){
callback.call(elem);
}
}
}(callback)
return options;
},
/**
* Maintain setInterval function and start animation
*/
tick : function(){
var _this = this;
if(!_this.timer){
_this.timer = setInterval(function(){
for(var i = 0, len = _this.fxMap.length; i < len; i ){
var elem = _this.fxMap[i][0];
var core = _this.data(elem)[0];
core(elem);
}
},16);
}
},
/**
* Stop all animations
*/
stop : function(){
if(this.timer){
clearInterval(this.timer);
this.timer = undefined;
}
},
/**
* Store or take out the queue
* @param elem
*/
data : function(elem){
for(var i = 0, len = this.fxMap.length; i < len; i ){
var data = this.fxMap[i];
if(elem === data[0]){
return data[1];
}
}
this.fxMap.push([elem,[]]);
return this.fxMap[this.fxMap.length - 1][1];
},
/**
* Delete queue
* @param elem
*/
removeData : function(elem){
for(var i = 0, len = this.fxMap.length; i < len; i ){
var data = this.fxMap[i];
if(elem === data[0]){
this.fxMap.splice(i, 1);
if(this.isDataEmpty()){
this.stop();
}
}
}
},
isDataEmpty : function(){
return this.fxMap.length == 0;
}
}, $ = fxBase;
/**
* Core object, used to generate animation objects.
* @param elem
* @param props
* @param options
* @return {Object}
*/
function fxCore(elem, props, options){
this.elem = elem;
this.props = props;
this.options = options;
this.start();
}
fxCore.prototype = {
constructor : fxCore,
/**
* Add the animation function to the queue and start the animation.
*/
start : function(){
var cores = $.data(this.elem);
cores.push(this.step());
$.tick();
},
/**
* 核心方法,控制每一帧元素的状态。
* @return function
*/
step : function(){
var _this = this;
var fn = function(elem){
var t = Date.now() - this.startTime;
if(Date.now() if(t for(var i in this.target ){
if(typeof this.source[i]['val'] === 'number'){
var val = parseFloat((this.source[i]['val'] (this.target[ i]['val'] - this.source[i]['val']) * this.options.easing(t / this.options.duration)).toFixed(7));
}else{
var r = parseInt(this.source[i]['val']['r'] (this.target[i]['val']['r'] - this. source[i]['val']['r']) * this.options.easing(t / this.options.duration));
var g = parseInt(this.source[i]['val']['g'] (this.target[i]['val']['g'] - this.source[i][' val']['g']) * this.options.easing(t / this.options.duration));
var b = parseInt(this.source[i]['val']['b'] (this.target[i]['val']['b'] - this.source[i][' val']['b']) * this.options.easing(t / this.options.duration));
var val = 'rgb('r','g','b')';
}
$.setStyle(this.elem,i,val this.source[i]['unit']);
}
}else{
for(var i in this.target){
if(typeof this.target[i]['val'] === 'number'){
var val = this.target[i]['val'];
}else{
var val = 'rgb(' this.target[i]['val']['r'] ',' this.target[i]['val']['g' ] ',' this.target[i]['val']['b'] ')';
}
$.setStyle(elem,i,val this.source[i]['unit']);
}
var cores = $.data(elem);
cores.shift();
this.options.callback();
if(cores.length == 0){
$.setStyle(elem,'overflow',this.overflow);
$.removeData(elem);
}
}
}
回傳函數(elem){
if(!_this.startTime){
var source = {};
_this.target = _this.props;
for(var i in _this.props){
var val = $.getStyle(_this.elem, i);
source[i] = $.parseStyle(val);
}
_this.source = 來源;
_this.startTime = Date.now();
_this.overflow = $.getStyle(elem,'overflow');
$.setStyle(elem,'溢出','隱藏');
}
fn.call(_this,elem);
}
}
}
/**
* 外部介面類別。
*/
fx.prototype = {
建構子 :➡fx,
/**
* 動畫方法
* @param prop
* @param duration
* @param easing
* @param callback
* @return {Object}
* @param callback
* @return {Object}
* /
animate : function(prop,uration, easing,callback){
if(arguments.length == 3 && typeof easing === 'function'){ // 大多數時候用戶個第三個參數是回呼
回呼=緩動;
緩動=未定義;
}
var props = $.parseProp(prop);
var options = $.setOption(this.elem,duration,easing,callback);
var core = new fxCore(this.elem,props,options);
回傳這個;
},
/**
* 停止動畫方法
* 使用方法 catjs('your element id').stop();
*/
stop : function(){
$.removeData(this.elem);
}
}
win.catfx = catfx;
})(這個,文檔);


使用起來也比較簡單.直接catfx('ID').animate({'margin-left':200,'background-color':'#ff0000'},600,'easeOut ',功能(){});

跟jquery的使用方法差不多,如果不傳第二個參數,則預設為400毫秒。且總共只有三個參數,第三個參數為回呼。 },600,function (){alert('灑商是回呼函數~')});
相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!