首頁  >  文章  >  web前端  >  js動畫(animate)簡單引擎程式碼範例_javascript技巧

js動畫(animate)簡單引擎程式碼範例_javascript技巧

WBOY
WBOY原創
2016-05-16 17:47:201695瀏覽

用慣了jquery的同學,相信都很欣賞其動畫引擎。確實相對比較完善!如果,如果想像力夠豐富的話,相信可以做出超乎想像的效果。當然,跟2d庫比起來,還是相差相當一段距離。 jquery壓根也不是專門為動畫而設計的。模擬真實世界方面,還是不足的。但在web世界裡還是游刃有餘的。動畫其實一直是flash的專屬領地(web區哉)。只是它常常淪為駭客攻擊的漏洞所在,而且要裝插件,有時候文件實在太大,而且性耗實在是高啊。 html5出現後,其實adobe自己都轉移陣地到html5了。當然,我覺得很長一段時間內,flash是不會被放棄的。

長話短說,步入正題。仿照flash的動畫原理,自己寫了一個很簡單的js動畫引擎。

首先,用過flash的同學都知道。 flash有個時間線,上面佈滿了「幀」。其實每個畫面都是一個鏡頭,鏡頭連貫起來就是一副動畫效果。其實,這跟電影的原理也是一樣的,小時候玩過底片的都知道,對著光可以看到一副副的鏡頭。人眼分辨兩個畫面的連貫性是有時間限度的。如果想看不到兩個畫面變換時的閃爍大概30格/秒左右,影片是24格的。所以,如果能保證,動畫切換能保證每秒30次,基本上,就做到了動畫的流暢效果,但這取決環境。所以具體情況,具體而定,其實關於這方面的知識我也是一知半解。就這個動畫引擎而言,了解這麼多也差不多足夠了,有興趣可以找到相關知識!

下面開始說說設計原理。

首先需要一個幀頻,也就是多少幀每秒。如果有了總用時,就可以計算出整個動畫下來有多少個「畫面」(總幀數)。這種設計,顯然有個不足的地方,不能保證時間剛好是個整數幀。除非1ms一幀。這是一個網友提出來的,我覺得不好就沒有採用。所以這個引擎是有時間誤差的。有了總幀數,當動畫運行到最後一幀的時候,整個動畫也就播放完。如果需要重複播放,重新把目前影格歸0。這種動畫有一個好處,就可以直接運行到指定畫面。也就是flash裡的gotoAndStop和gotoAndPlay。其實整個動畫設計原理都是照著flash實現的。包括一個很重要的方法:enterFrame。位置是根據進入當前幀來計算的。還有其它一些方法:stop、play、next......等等因為目前來說,這個引擎是寫非常簡單和粗糙的,先不說這麼詳細了。下面先上程式碼和範例吧!

animate.js 動畫核心

複製程式碼 程式碼如下:

var animation = function(obj) {
    this.obj = obj;
    this.frames = 0;
    this.timmer = undefined;
    this.running = false;
    this.ms = [];
}

animation.prototype = {
    fps: 36,
    init: function(props, duration, tween) {
        //console.log('初始化');
        this.curframe = 0;
        this.initstate = {};
        this.props = props;
        this.duration = duration || 1000;
        this.tween = tween || function(t, b, c, d) {
            return t * c / d + b;
        };
        this.frames = Math.ceil(this.duration * this.fps/1000);
        for (var prop in this.props) {
            this.initstate[prop] = {
                from: parseFloat($util.dom.getStyle(this.obj, prop)),
                to: parseFloat(this.props[prop])
            };
        }
    },
    start: function() {
        if (!this.running && this.hasNext()) {
            //console.log('可以执行...');
            this.ms.shift().call(this)
        }
        return this;
    },
    //开始播放
    play: function(callback) {
        //console.log('开始动画!');
        var that = this;

        this.running = true;

        if (this.timmer) {
            this.stop();
        }

        this.timmer = setInterval(function() {
            if (that.complete()) {
                that.stop();
                that.running = false;
                if (callback) {
                    callback.call(that);
                }
                return;
            }
            that.curframe++;
            that.enterFrame.call(that);
        },
 / this.fps);

        return this;
    },
    // 停止动画
    stop: function() {
        //console.log('结束动画!');
        if (this.timmer) {
            clearInterval(this.timmer);
            // 清除掉timmer id
            this.timmer = undefined;
        }

    },
    go: function(props,uration, tween) {
        var that =  this.ms.push(function() {
            that.init.call(that、props、duration、tween);
                 返回此;
},
    // 平滑一格
    next: function() {
        this.stop();
       this.stop();
       this.stop();
 this.curframe >;這個.frames this.frames: this.curframe;
        this.enterFrame.call(this);
    },
    //向前一幀
    prev: function() {
        this.stop ( );
        this.curframe--;
        this.curframe = this.curframe         this.enterFrame.call(this);
    },
    //  this. stop ();
        this.curframe = frame;
        this.play.call(this);        this.stop();
        this.curframe = frame;
     🎜>    EnterFrame: function ( ) {
        //console.log('進入影格:' this.curframe)
        var ds;            ds = this.tween(this.curframe, this.initstate[prop]['from'], this.initstate[p][ ] - this.initstate[prop]['from'], this.frames).toFixed(2);
            //console.log(prop ':' ds) . obj, prop, ds)
        }
    },
    //動畫結束
   🎜>    },
    hasNext: function() {
        return this.ms.length >; 0;
    }
}


以下是一個簡單的工具,其中有一些有用的緩動公式:

util.js





複製程式碼


程式碼如下:


$util = {
    /**
    * 類型偵測
   */
    type : function(obj){
     type : function(obj){
     rep var str = Object.prototype.toString.call(obj).toLowerCase();
        str.match(rep);
        return RegExp.$1;
    },
    /**
    * 深拷貝
    */
    $unlink :function (object){
        var unlinked;
       :
                unlinked = {};
為 (var p in object) {
                    unlinked[p] = $unlink(object[p]          break;
            case 'array':
          ;
                for (var i = 0, l = object.length; i    
                }
           時與休息者
            預設:返回物件;
        }
       >    dom:{
        $: function(id) {
            return document.getElementById(id);
        },
       var style = obj.currentStyle || window.getCompulatedStyle(obj, '');
            if (obj.style.filter) {
     🎜>            }
return style[prop];
        },
        setStyle: function(obj, prop        case 'opacity':
                if($util.client .browser.ie){
                    obj.style.filter = 'alpha(' prop '=' 嗚
                    obj.style[prop] ;
}
                月;
             >                ;
            }
    ,
        setStyles: function(obj, props) {
            🎜>                case 'opacity':
             browser.ie){
                       obj.style.filter = 'alpha(             }else{
                     
                     }
                    ;
               默認值:
                    obj.style[prop] = props[prop] 'px';
                    中斷;
                }
            }
        }
    },
    /**
    *Event 事件相關
   */
    evt : {
          if (oTarget.addEventListener) {
                o addEventListener (sEventType, fnHandler, false);
            } else if (oTarget.attachEvent) {
               } else {
                oTarget[" on" sEventType ] = fnHandler;
            }
        },
            if (oTarget.removeEventListener) {
                oTarget.removeListener(sEventType, fnHandler, false );
            } else if (oTarget.detachEvent) {
                } else {
                o目標[「on」sEventType] = null ;
            }
        }
    },
    /**
    *Ajax 非同步載入
   */
    ajax : {
        request:function (options) {
                var url = options.url,
           = options.context,
                    success = options.success,                       headers = options.headers;
                 試試{
                        xhr = new ActiveXObject(' MSXML2.XMLHTTP');
                    } catch(e) {
   XMLHTTP');
                    }
              xhr.onreadystatechange = function( ) {
                    if (xhr.readyState == 4 && xhr.stat }responseText;
                      .res); xhr.open(type, url, async);
                xhr.send(send);
 🎜>    清單: {
minIndex : function(ary){
            return Math.min.apply(null,ary);   
        },
          },
        maxitem : function(ary){
       🎜>    },
    /**
    *Client 客户端检测
    */
    client : function(){
        // 浏览器渲染引擎 engines
        var engine = {           
            ie: 0,
            gecko: 0,
            webkit: 0,
            khtml: 0,
            opera: 0,

            //complete version
            ver: null 
        };

        // 浏览器
        var browser = {
            //browsers
            ie: 0,
            firefox: 0,
            safari: 0,
            konq: 0,
            opera: 0,
            chrome: 0,
            //specific version
            ver: null
        };

        // 客户端平台platform/device/OS
        var system = {
            win: false,
            mac: false,
            x11: false,

            //移动设备
            iphone: false,
            ipod: false,
            ipad: false,
            ios: false,
            android: false,
            nokiaN: false,
            winMobile: false,

            //game systems
            wii: false,
            ps: false
        };   

        // 偵測瀏覽器引擎
        var ua = navigator.userAgent;   
        if (window.opera){
            engine.ver = browser.ver = window .a.); = parseFloat(engine.ver);
} else if (/AppleWebKit/(S )/.test(ua)){
            engine.ver = RegExp["$1"];            //判斷為Chrome 或Safari
            browser.ver = RegExp["$1"];
                browser.chrome = parseFloat (browser.ver);
            } else if (/Version/(S )/.test(ua)){
                   browser.safari = parseFloat( browser.ver);
            } else {
              = 1;
                if (engine.webkit
100){
        } else if (engine.webkit                     safari   412){
                    safariVersion = 1.3;
                safariVersion = 2;
                }  

                 
            }
        } else if (/KHTML/(S )/.test(ua)    engine.ver = browser .ver = RegExp["$1"];
            engine.khtml = browser.konq = parseFloat(engine.      engine.khtml = browser.konq = parseFloat(engine. );
  :   }/.test(ua)){   
            engine.ver = RegExp["$1"];
                 // 判斷是否為Firefox
            if (/Firefox/(S )/.test(ua)){
                   browser.firefox = parseFloat(browser.ver);
           }
        } else if (/MSIE ([^;] )/.test(ua)){   
             engine.ie = 瀏覽器。

        //detect browsers
        browser.ie = engine.ie;
        browser.opera = engine.opera;
       

        //detect platform
        var p = navigator.platform;
        system.win = p.indexOf("Win") == 0;
        system.mac = p.indexOf("Mac") == 0;
        system.x11 = (p == "X11") || (p.indexOf("Linux") == 0);

        //偵測Windows 作業系統
       if (system.win){
         ){
        .test(ua)){
                if (RegExp["$1"] == "NT"){
   🎜>                        case "5.0":
    .win = "2000";
                           中斷;
                       案例"5.1":
                            system.win = "XP";
                            中斷;
                        case "6.0":
                            system.win = "Vista";
                             .1":
                                   中斷;
                          system.win = "NT";
                            的休息;      }        }                                               系統。 win = "ME";
                } else {
                      }
            }
       >        system.iphone = ua.indexOf("iPhone") >; -1;
        system.ipod = ua.index ") > -1;
        system.nokiaN = ua.indexOf("NokiaN") > -1;

      
            system.winMobile = system.win;
        } else if (system.win == "Ph"){
            if(/Windows Phone OS (\d+.\d+)/.test(ua)){;
                system.win = "Phone";
                system.winMobile = parseFloat(RegExp["$1"]);
            }
        }

        //determine iOS version
        if (system.mac && ua.indexOf("Mobile") > -1){
            if (/CPU (?:iPhone )?OS (\d+_\d+)/.test(ua)){
                system.ios = parseFloat(RegExp.$1.replace("_", "."));
            } else {
                system.ios = 2;  //can't really detect - so guess
            }
        }

        //determine Android version
        if (/Android (\d+\.\d+)/.test(ua)){
            system.android = parseFloat(RegExp.$1);
        }

        //gaming systems
        system.wii = ua.indexOf("Wii") > -1;
        system.ps = /playstation/i.test(ua);

        //return it
        return {
            engine:     engine,
            browser:    browser,
            system:     system       
        };

    }(),
    /**
    *Tween 緩動相關性
   */
    補間:{
      / d b ;
        },
        四邊形:{
               return c * (t /= d) * t b;
            },
easeOut: function(t, b, c, d) {
                return - c * (t /= d) * (t - 2) b;                if ((t /= d / 2)             }
        },
          },
          },
     c, d) {
                return c * (t /= d) * t * t b;
            },
              t = t / d - 1) * t * t 1) b;
            },
            easeInOut: function(t, b, c, 2)                 return c / 2 * ((t -= 2) * t * t 2) b;
           Quart: {
            easyIn: function(t, b, 、c、 d){
回傳c *(t /= d) * t * t * t * t b; },
> sieleout:function(t,b,b,c,d){回傳-c * ((t = t / d - 1) * t * t * t - 1) b;
            },
          },
          },
         >                if ((t / = d/2)    - 2) b;
            }
        },
      c, d) {
                return c * (t /= d) * t * t * t * t b;
            },
           c * ((t = t / d - 1) * t * t * t * t 1) b;
            },
            easeInOut: function(t, b, c, d) {
            🎜 >               return c / 2 * ((t -= 2) * t * t * t * t 2) b;
           正弦:{
            easyIn :函數(t , b , c, d) {
                return - c * Math.cos(t / d * (Math.PI / 2)) c b     easeOut: function(t, b, c, d ) {
                return c * Math.sin(t / d * (Math.PI / 2)) b;
   escapeInOut: function(t, b, c, d) {
return - c / 2 * (Math.cos(Math.PI * t / d) - 1) b;
            }
              easyIn: function(t, b , c, d) {
                返回(t == 0) ? b: c * Math.pow(2, 10 * (t / d - 1)) b;
            },
          },
          },
          },
                 return (t = = d) ? b c: c * ( - Math.pow(2, -10 * t / d) 1) b;
            },
          },
          },
          },
                 if (t == 0) return b;
                if (t == d) return b c;
       ow(2, 10 * ( t - 1)) b;
                return c / 2 * ( - Math.pow(2, -10 * --t) 2) b ,
        循環: {
            easeIn: function(t, b, c, d) {
                       },
            easeOut: function(t, b, c, d) {
                     },
            escapeInOut :函數(t, b, c, d) {
                if ((t /= d / 2)                 return c / 2 * (Math.sqrt(1 - (t -= 2) * t) 1) b;        彈性: {
            easeIn: function(t, b, c, d, a, p 𠟠)> 🎜>                if ((t /= d ) == 1) return b c;
                if (!p) p = d * .3;
                        a = c;
                    var s = p / 4;
       🎜>                則 - (a * Math.pow(2 ) ) , 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) b;
           t , b, c, d, a, p) {
                if (t == 0) return b;
                    if (! p ) p = d * .3;
               if (!a || a                   var s = p / 4;
                } 其他變數s = p / (2 * Math.PI) * Math.asin(c / a);
                return (a * Math.pow(2, -10 * t) * Math.sin((t * d - -sin s) ) ) * (2 * Math.PI) / p) c b);
            },
                  if (t = = 0 ) return b;
               
                if ( !a |一個                    a = c;
                  } else var s = p / (2 * Math.PI) * Math .asin (c / a );
                if (t                 return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * d - s) * ( 2 * 數學.PI) / p) * .5 c b;
            }
         easyIn: 函數(t, b, c, d, s) {
if ( s ==未定義) s = 1.70158;
                return c * (t /= ,
            easeOut: function(t, b, c, d, s) {
                       return c * ((t = t / d - 1) * t * ((s 1) * t s) 1) b;
            },
                if (s == undefined) s = 1.70158 ;
                if ((t /= d / 2)             }
          }
       🎜> lisein:函數(t,b,c,d){}, ieseout: ( t,b,c,d){
> if(((t / = d)<(1 / 2.75)){
返回c *(7.5625 * t * t * t)b;
} else if (t                    ,           } else if (t                     return c * (7.5625 * (t -        } else {
                    返回 c *(7.5625 * (t - = (2.625 / 2.75)) * t .984375) b;
                }
          }                若(t                /且為 0,5,Bounce.easeOut(t * 2 - d * 5, d * .5 b;
            }
        }
    }

}



下面是個應用:



複製程式碼

程式碼如下:






无标题文档




   


       

       

           

                   

  •                

  •                

  •                

  •                

  •                

  •                

  •                

  •            

       

       

   

   
        /**
        * @para obj  內容對象
        * @para lbtn 左鈕
     每次滾動的寬
        * @para duration 每次運行時間
        * @para tween 緩動型
       */
        function scOnce(obj, lbtn, rbtn, wutouto    var am = 新動畫(_ul ) ,
               //    timmerm
                dr = '左',
        最右端?
            函數isr (){
                      // 最左端?
            function isl(){
return ulen - Math.abs(parseInt($util.dom.getStyle(obj, 'left'))-10 < ;=w;   
         isl())
            return;
            // 左移
             步驟= -1* w;
                am.go({left:step "px"},duration ,tween).start();   
            }
                           step = w;
               " },持續時間,補間)。開始();   
            }

           lick',function(){
                isl()? that.goright ():that .goleft();
            })
            // unction(){
                isr()? that.goleft( ):that.goright();
            })

        

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn