简单的动画引擎
Posted codeing or artist ?
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简单的动画引擎相关的知识,希望对你有一定的参考价值。
<div id="box" style="position:absolute;">Hello!</div>
var timers = { timerID:0, timers:[], add:function(fn){ this.timers.push(fn); }, start:function(){ if(this.timerID) return; (function runNext(){ if(timers.timers.length > 0){ for(var i=0; i<timers.timers.length; i++){ if(timers.timers[i]() === false){ timers.timers.splice(i,1); i--; } } timers.timersID = setTimeout(runNext,0); } })(); }, stop:function(){ clearTimeout(this.timerID); this.timerID = 0; } }; var box = document.getElementById(‘box‘), x = 0, y = 20; timers.add(function(){ box.style.left = x + ‘px‘; if(++x > 50) return false; }); timers.add(function(){ box.style.top = y + ‘px‘; y += 2; if(y > 120) return false; }); timers.start();
在此基础上再扩展一下:
var timers = function(speed,callback){ var cacheID = 0, cache = []; var timers = { add:function(fn){ cache.push(fn); }, start:function(){ if(cacheID) return; (function runNext(){ if(cache.length > 0){ for(var i=0; i<cache.length; i++){ if(cache[i]() === false){ cache.splice(i,1); i--; } } cacheID = setTimeout(runNext,speed || 0); }else{ timers.stop(); } })(); }, stop:function(){ clearTimeout(cacheID); cacheID = 0; callback && callback(); } }; return timers; }; var animate = function(el,params,speed,callback){ if(!el) return; var t = timers(speed,callback); for(var n in params){ var target = parseFloat(params[n]) || 0; var b = parseFloat(self.currentStyle(el)[n]) || el["offset" + n.substring(0,1).toUpperCase() + n.substring(1)] || 0; (function(target,b,n){ t.add(function(){ el.style[n] = b + ‘px‘; if(++b > target) return false; }); })(target,b,n); } t.start(); }; var box = document.getElementById(‘box‘); var box2 = document.getElementById(‘box2‘); animate(box,{‘left‘:200,‘top‘:500,‘fontSize‘:40},10,function(){ alert(‘动画结束啦‘); }); animate(box2,{‘left‘:400,‘top‘:300,‘fontSize‘:80},10,function(){ alert(‘动画结束啦‘); });
以上是关于简单的动画引擎的主要内容,如果未能解决你的问题,请参考以下文章