您好,欢迎访问一九零五行业门户网

js动画(animate)简单引擎代码示例_javascript技巧

用惯了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, duration, tween) {
        var that = this;
        //console.log(tween)
        this.ms.push(function() {
            that.init.call(that, props, duration, tween);
            that.play.call(that, that.start);
        });
        return this;
    },
    //向后一帧
    next: function() {
        this.stop();
        this.curframe++;
        this.curframe = this.curframe > this.frames ? this.frames: this.curframe;
        this.enterframe.call(this);
    },
    //向前一帧
    prev: function() {
        this.stop();
        this.curframe--;
        this.curframe = this.curframe         this.enterframe.call(this);
    },
    //跳跃到指定帧并播放
    gotoandplay: function(frame) {
        this.stop();
        this.curframe = frame;
        this.play.call(this);
    },
    //跳到指定帧停止播放
    gotoandstop: function(frame) {
        this.stop();
        this.curframe = frame;
        this.enterframe.call(this);
    },
    //进入帧动作
    enterframe: function() {
        //console.log('进入帧:' + this.curframe)
        var ds;
        for (var prop in this.initstate) {
            //console.log('from: ' + this.initstate[prop]['from'])
            ds = this.tween(this.curframe, this.initstate[prop]['from'], this.initstate[prop]['to'] - this.initstate[prop]['from'], this.frames).tofixed(2);
            //console.log(prop + ':' + ds)
            $util.dom.setstyle(this.obj, prop, ds)
        }
    },
    //动画结束
    complete: function() {
        return this.curframe >= this.frames;
    },
    hasnext: function() {
        return this.ms.length > 0;
    }
}
下面是一个简单的工具,其中有所用到的缓动公式:util.js
复制代码 代码如下:
$util = {
    /**
    * 类型检测
    */
    type : function(obj){
        var rep = /\[object\s+(\w+)\]/i;
        var str = object.prototype.tostring.call(obj).tolowercase();
        str.match(rep);
        return regexp.$1;
    },
    /**
    * 深拷贝
    */
    $unlink :function (object){
        var unlinked;
        switch ($type(object)){
            case 'object':
                unlinked = {};
                for (var p in object) {
                    unlinked[p] = $unlink(object[p]);
                }
            break;
            case 'array':
                unlinked = [];
                for (var i = 0, l = object.length; i                     unlinked[i] = $unlink(object[i]);
                }
            break;
            default: return object;
        }
        return unlinked;
    },
    /**
    *dom 相关操作
    */
    dom:{
        $: function(id) {
            return document.getelementbyid(id);
        },
        getstyle: function(obj, prop) {
            var style = obj.currentstyle || window.getcomputedstyle(obj, '');
            if (obj.style.filter) {
                return obj.style.filter.match(/\d+/g)[0];
            }
            return style[prop];
        },
        setstyle: function(obj, prop, val) {
            switch (prop) {
            case 'opacity':
                if($util.client.browser.ie){
                    obj.style.filter = 'alpha(' + prop + '=' + val*100 + ')'   
                }else{
                    obj.style[prop] = val;
                }
                break;
            default:
                obj.style[prop] = val + 'px';
                break;
            }
        },
        setstyles: function(obj, props) {
            for (var prop in props) {
                switch (prop) {
                case 'opacity':
                    if($util.client.browser.ie){
                        obj.style.filter = 'alpha(' + prop + '=' + props[prop] + ')'       
                    }else{
                        obj.style[prop] = props[prop];
                    }
                    break;
                default:
                    obj.style[prop] = props[prop] + 'px';
                    break;
                }
            }
        }
    },
    /**
    *event 事件相关
    */
    evt : {
        addevent : function(otarget, seventtype, fnhandler) {
            if (otarget.addeventlistener) {
                otarget.addeventlistener(seventtype, fnhandler, false);
            } else if (otarget.attachevent) {
                otarget.attachevent(on + seventtype, fnhandler);
            } else {
                otarget[on + seventtype] = fnhandler;
            }
        },
        rmevent : function removeeventhandler (otarget, seventtype, fnhandler) {
            if (otarget.removeeventlistener) {
                otarget.removeeventlistener(seventtype, fnhandler, false);
            } else if (otarget.detachevent) {
                otarget.detachevent(on + seventtype, fnhandler);
            } else {
                otarget[on + seventtype] = null;
            }
        }
    },
    /**
    *ajax 异步加载
    */
    ajax : {
        request:function (options) {
                var xhr, res;
                var url = options.url,
                    context = options.context,
                    success = options.success,
                    type = options.type,
                    datatype = options.datatype,
                    async = options.async,
                    send = options.send,
                    headers = options.headers;
try {
                    xhr = new xmlhttprequest();
                } catch(e) {
                    try {
                        xhr = new activexobject('msxml2.xmlhttp');
                    } catch(e) {
                        xhr = new activexobject('microsoft.xmlhttp');
                    }
                }
xhr.onreadystatechange = function() {
                    if (xhr.readystate == 4 && xhr.status == 200) {
                        res = xhr.responsetext;
                        success(res);
                    }
                }
                xhr.open(type, url, async);
                xhr.send(send);
        }
    },
    /**
    *array 数组相关
    */
    array : {
        minindex : function(ary){
            return math.min.apply(null,ary);   
        },
        maxitem : function(ary){
            return math.max.apply(null,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.opera.version();
            engine.opera = browser.opera = parsefloat(engine.ver);
        } else if (/applewebkit\/(\s+)/.test(ua)){
            engine.ver = regexp[$1];
            engine.webkit = parsefloat(engine.ver);
//figure out if it's chrome or safari
            if (/chrome\/(\s+)/.test(ua)){
                browser.ver = regexp[$1];
                browser.chrome = parsefloat(browser.ver);
            } else if (/version\/(\s+)/.test(ua)){
                browser.ver = regexp[$1];
                browser.safari = parsefloat(browser.ver);
            } else {
                //approximate version
                var safariversion = 1;
                if (engine.webkit                     safariversion = 1;
                } else if (engine.webkit                     safariversion = 1.2;
                } else if (engine.webkit                     safariversion = 1.3;
                } else {
                    safariversion = 2;
                }
browser.safari = browser.ver = safariversion;       
            }
        } else if (/khtml\/(\s+)/.test(ua) || /konqueror\/([^;]+)/.test(ua)){
            engine.ver = browser.ver = regexp[$1];
            engine.khtml = browser.konq = parsefloat(engine.ver);
        } else if (/rv:([^\)]+)\) gecko\/\d{8}/.test(ua)){   
            engine.ver = regexp[$1];
            engine.gecko = parsefloat(engine.ver);
//determine if it's firefox
            if (/firefox\/(\s+)/.test(ua)){
                browser.ver = regexp[$1];
                browser.firefox = parsefloat(browser.ver);
            }
        } else if (/msie ([^;]+)/.test(ua)){   
            engine.ver = browser.ver = regexp[$1];
            engine.ie = browser.ie = parsefloat(engine.ver);
        }
//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);
        //detect windows operating systems
        if (system.win){
            if (/win(?:dows )?([^do]{2})\s?(\d+\.\d+)?/.test(ua)){
                if (regexp[$1] == nt){
                    switch(regexp[$2]){
                        case 5.0:
                            system.win = 2000;
                            break;
                        case 5.1:
                            system.win = xp;
                            break;
                        case 6.0:
                            system.win = vista;
                            break;
                        case 6.1:
                            system.win = 7;
                            break;
                        default:
                            system.win = nt;
                            break;               
                    }                           
                } else if (regexp[$1] == 9x){
                    system.win = me;
                } else {
                    system.win = regexp[$1];
                }
            }
        }
//mobile devices
        system.iphone = ua.indexof(iphone) > -1;
        system.ipod = ua.indexof(ipod) > -1;
        system.ipad = ua.indexof(ipad) > -1;
        system.nokian = ua.indexof(nokian) > -1;
//windows mobile
        if (system.win == ce){
            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 缓动相关
    */
    tween: {
        linear: function(t, b, c, d) {
            return c * t / d + b;
        },
        quad: {
            easein: function(t, b, c, d) {
                return c * (t /= d) * t + b;
            },
            easeout: function(t, b, c, d) {
                return - c * (t /= d) * (t - 2) + b;
            },
            easeinout: function(t, b, c, d) {
                if ((t /= d / 2)                 return - c / 2 * ((--t) * (t - 2) - 1) + b;
            }
        },
        cubic: {
            easein: function(t, b, c, d) {
                return c * (t /= d) * t * t + b;
            },
            easeout: function(t, b, c, d) {
                return c * ((t = t / d - 1) * t * t + 1) + b;
            },
            easeinout: function(t, b, c, d) {
                if ((t /= d / 2)                 return c / 2 * ((t -= 2) * t * t + 2) + b;
            }
        },
        quart: {
            easein: function(t, b, c, d) {
                return c * (t /= d) * t * t * t + b;
            },
            easeout: function(t, b, c, d) {
                return - c * ((t = t / d - 1) * t * t * t - 1) + b;
            },
            easeinout: function(t, b, c, d) {
                if ((t /= d / 2)                 return - c / 2 * ((t -= 2) * t * t * t - 2) + b;
            }
        },
        quint: {
            easein: function(t, b, c, d) {
                return c * (t /= d) * t * t * t * t + b;
            },
            easeout: function(t, b, c, d) {
                return c * ((t = t / d - 1) * t * t * t * t + 1) + b;
            },
            easeinout: function(t, b, c, d) {
                if ((t /= d / 2)                 return c / 2 * ((t -= 2) * t * t * t * t + 2) + b;
            }
        },
        sine: {
            easein: function(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;
            },
            easeinout: function(t, b, c, d) {
                return - c / 2 * (math.cos(math.pi * t / d) - 1) + b;
            }
        },
        expo: {
            easein: function(t, b, c, d) {
                return (t == 0) ? b: c * math.pow(2, 10 * (t / d - 1)) + b;
            },
            easeout: function(t, b, c, d) {
                return (t == d) ? b + c: c * ( - math.pow(2, -10 * t / d) + 1) + b;
            },
            easeinout: function(t, b, c, d) {
                if (t == 0) return b;
                if (t == d) return b + c;
                if ((t /= d / 2)                 return c / 2 * ( - math.pow(2, -10 * --t) + 2) + b;
            }
        },
        circ: {
            easein: function(t, b, c, d) {
                return - c * (math.sqrt(1 - (t /= d) * t) - 1) + b;
            },
            easeout: function(t, b, c, d) {
                return c * math.sqrt(1 - (t = t / d - 1) * t) + b;
            },
            easeinout: function(t, b, c, d) {
                if ((t /= d / 2)                 return c / 2 * (math.sqrt(1 - (t -= 2) * t) + 1) + b;
            }
        },
        elastic: {
            easein: function(t, b, c, d, a, p) {
                if (t == 0) return b;
                if ((t /= d) == 1) return b + c;
                if (!p) p = d * .3;
                if (!a || a                     a = c;
                    var s = p / 4;
                } else var s = p / (2 * math.pi) * math.asin(c / a);
                return - (a * math.pow(2, 10 * (t -= 1)) * math.sin((t * d - s) * (2 * math.pi) / p)) + b;
            },
            easeout: function(t, b, c, d, a, p) {
                if (t == 0) return b;
                if ((t /= d) == 1) return b + c;
                if (!p) p = d * .3;
                if (!a || a                     a = c;
                    var s = p / 4;
                } else var s = p / (2 * math.pi) * math.asin(c / a);
                return (a * math.pow(2, -10 * t) * math.sin((t * d - s) * (2 * math.pi) / p) + c + b);
            },
            easeinout: function(t, b, c, d, a, p) {
                if (t == 0) return b;
                if ((t /= d / 2) == 2) return b + c;
                if (!p) p = d * (.3 * 1.5);
                if (!a || a                     a = c;
                    var s = p / 4;
                } 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 * math.pi) / p) * .5 + c + b;
            }
        },
        back: {
            easein: function(t, b, c, d, s) {
                if (s == undefined) s = 1.70158;
                return c * (t /= d) * t * ((s + 1) * t - s) + b;
            },
            easeout: function(t, b, c, d, s) {
                if (s == undefined) s = 1.70158;
                return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
            },
            easeinout: function(t, b, c, d, s) {
                if (s == undefined) s = 1.70158;
                if ((t /= d / 2)                 return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
            }
        },
        bounce: {
            easein: function(t, b, c, d) {
                return c - tween.bounce.easeout(d - t, 0, c, d) + b;
            },
            easeout: function(t, b, c, d) {
                if ((t /= d)                     return c * (7.5625 * t * t) + b;
                } else if (t                     return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b;
                } else if (t                     return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b;
                } else {
                    return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b;
                }
            },
            easeinout: function(t, b, c, d) {
                if (t                 else return tween.bounce.easeout(t * 2 - d, 0, c, d) * .5 + c * .5 + b;
            }
        }
    }
}
下面是个应用:
复制代码 代码如下:
其它类似信息

推荐信息