js动画(animate)简单引擎代码示例
用惯了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动画核心
varanimation=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){
returnt*c/d+b;
};
this.frames=Math.ceil(this.duration*this.fps/1000);
for(varpropinthis.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)
}
returnthis;
},
//开始播放
play:function(callback){
//console.log("开始动画!");
varthat=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);
returnthis;
},
//停止动画
stop:function(){
//console.log("结束动画!");
if(this.timmer){
clearInterval(this.timmer);
//清除掉timmerid
this.timmer=undefined;
}
},
go:function(props,duration,tween){
varthat=this;
//console.log(tween)
this.ms.push(function(){
that.init.call(that,props,duration,tween);
that.play.call(that,that.start);
});
returnthis;
},
//向后一帧
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<0?0: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)
vards;
for(varpropinthis.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(){
returnthis.curframe>=this.frames;
},
hasNext:function(){
returnthis.ms.length>0;
}
}
下面是一个简单的工具,其中有所用到的缓动公式:
util.js
$util={
/**
*类型检测
*/
type:function(obj){
varrep=/\[object\s+(\w+)\]/i;
varstr=Object.prototype.toString.call(obj).toLowerCase();
str.match(rep);
returnRegExp.$1;
},
/**
*深拷贝
*/
$unlink:function(object){
varunlinked;
switch($type(object)){
case"object":
unlinked={};
for(varpinobject){
unlinked[p]=$unlink(object[p]);
}
break;
case"array":
unlinked=[];
for(vari=0,l=object.length;i<l;i++){
unlinked[i]=$unlink(object[i]);
}
break;
default:returnobject;
}
returnunlinked;
},
/**
*Dom相关操作
*/
dom:{
$:function(id){
returndocument.getElementById(id);
},
getStyle:function(obj,prop){
varstyle=obj.currentStyle||window.getComputedStyle(obj,"");
if(obj.style.filter){
returnobj.style.filter.match(/\d+/g)[0];
}
returnstyle[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(varpropinprops){
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);
}elseif(oTarget.attachEvent){
oTarget.attachEvent("on"+sEventType,fnHandler);
}else{
oTarget["on"+sEventType]=fnHandler;
}
},
rmEvent:functionremoveEventHandler(oTarget,sEventType,fnHandler){
if(oTarget.removeEventListener){
oTarget.removeEventListener(sEventType,fnHandler,false);
}elseif(oTarget.detachEvent){
oTarget.detachEvent("on"+sEventType,fnHandler);
}else{
oTarget["on"+sEventType]=null;
}
}
},
/**
*Ajax异步加载
*/
ajax:{
request:function(options){
varxhr,res;
varurl=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=newXMLHttpRequest();
}catch(e){
try{
xhr=newActiveXObject("MSXML2.XMLHTTP");
}catch(e){
xhr=newActiveXObject("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){
returnMath.min.apply(null,ary);
},
maxitem:function(ary){
returnMath.max.apply(null,ary);
}
},
/**
*Client客户端检测
*/
client:function(){
//浏览器渲染引擎engines
varengine={
ie:0,
gecko:0,
webkit:0,
khtml:0,
opera:0,
//completeversion
ver:null
};
//浏览器
varbrowser={
//browsers
ie:0,
firefox:0,
safari:0,
konq:0,
opera:0,
chrome:0,
//specificversion
ver:null
};
//客户端平台platform/device/OS
varsystem={
win:false,
mac:false,
x11:false,
//移动设备
iphone:false,
ipod:false,
ipad:false,
ios:false,
android:false,
nokiaN:false,
winMobile:false,
//gamesystems
wii:false,
ps:false
};
//检测浏览器引擎
varua=navigator.userAgent;
if(window.opera){
engine.ver=browser.ver=window.opera.version();
engine.opera=browser.opera=parseFloat(engine.ver);
}elseif(/AppleWebKit\/(\S+)/.test(ua)){
engine.ver=RegExp["$1"];
engine.webkit=parseFloat(engine.ver);
//figureoutifit"sChromeorSafari
if(/Chrome\/(\S+)/.test(ua)){
browser.ver=RegExp["$1"];
browser.chrome=parseFloat(browser.ver);
}elseif(/Version\/(\S+)/.test(ua)){
browser.ver=RegExp["$1"];
browser.safari=parseFloat(browser.ver);
}else{
//approximateversion
varsafariVersion=1;
if(engine.webkit<100){
safariVersion=1;
}elseif(engine.webkit<312){
safariVersion=1.2;
}elseif(engine.webkit<412){
safariVersion=1.3;
}else{
safariVersion=2;
}
browser.safari=browser.ver=safariVersion;
}
}elseif(/KHTML\/(\S+)/.test(ua)||/Konqueror\/([^;]+)/.test(ua)){
engine.ver=browser.ver=RegExp["$1"];
engine.khtml=browser.konq=parseFloat(engine.ver);
}elseif(/rv:([^\)]+)\)Gecko\/\d{8}/.test(ua)){
engine.ver=RegExp["$1"];
engine.gecko=parseFloat(engine.ver);
//determineifit"sFirefox
if(/Firefox\/(\S+)/.test(ua)){
browser.ver=RegExp["$1"];
browser.firefox=parseFloat(browser.ver);
}
}elseif(/MSIE([^;]+)/.test(ua)){
engine.ver=browser.ver=RegExp["$1"];
engine.ie=browser.ie=parseFloat(engine.ver);
}
//detectbrowsers
browser.ie=engine.ie;
browser.opera=engine.opera;
//detectplatform
varp=navigator.platform;
system.win=p.indexOf("Win")==0;
system.mac=p.indexOf("Mac")==0;
system.x11=(p=="X11")||(p.indexOf("Linux")==0);
//detectwindowsoperatingsystems
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;
}
}elseif(RegExp["$1"]=="9x"){
system.win="ME";
}else{
system.win=RegExp["$1"];
}
}
}
//mobiledevices
system.iphone=ua.indexOf("iPhone")>-1;
system.ipod=ua.indexOf("iPod")>-1;
system.ipad=ua.indexOf("iPad")>-1;
system.nokiaN=ua.indexOf("NokiaN")>-1;
//windowsmobile
if(system.win=="CE"){
system.winMobile=system.win;
}elseif(system.win=="Ph"){
if(/WindowsPhoneOS(\d+.\d+)/.test(ua)){;
system.win="Phone";
system.winMobile=parseFloat(RegExp["$1"]);
}
}
//determineiOSversion
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"treallydetect-soguess
}
}
//determineAndroidversion
if(/Android(\d+\.\d+)/.test(ua)){
system.android=parseFloat(RegExp.$1);
}
//gamingsystems
system.wii=ua.indexOf("Wii")>-1;
system.ps=/playstation/i.test(ua);
//returnit
return{
engine: engine,
browser: browser,
system: system
};
}(),
/**
*Tween缓动相关
*/
tween:{
Linear:function(t,b,c,d){
returnc*t/d+b;
},
Quad:{
easeIn:function(t,b,c,d){
returnc*(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)<1)returnc/2*t*t+b;
return-c/2*((--t)*(t-2)-1)+b;
}
},
Cubic:{
easeIn:function(t,b,c,d){
returnc*(t/=d)*t*t+b;
},
easeOut:function(t,b,c,d){
returnc*((t=t/d-1)*t*t+1)+b;
},
easeInOut:function(t,b,c,d){
if((t/=d/2)<1)returnc/2*t*t*t+b;
returnc/2*((t-=2)*t*t+2)+b;
}
},
Quart:{
easeIn:function(t,b,c,d){
returnc*(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)<1)returnc/2*t*t*t*t+b;
return-c/2*((t-=2)*t*t*t-2)+b;
}
},
Quint:{
easeIn:function(t,b,c,d){
returnc*(t/=d)*t*t*t*t+b;
},
easeOut:function(t,b,c,d){
returnc*((t=t/d-1)*t*t*t*t+1)+b;
},
easeInOut:function(t,b,c,d){
if((t/=d/2)<1)returnc/2*t*t*t*t*t+b;
returnc/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){
returnc*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)returnb;
if(t==d)returnb+c;
if((t/=d/2)<1)returnc/2*Math.pow(2,10*(t-1))+b;
returnc/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){
returnc*Math.sqrt(1-(t=t/d-1)*t)+b;
},
easeInOut:function(t,b,c,d){
if((t/=d/2)<1)return-c/2*(Math.sqrt(1-t*t)-1)+b;
returnc/2*(Math.sqrt(1-(t-=2)*t)+1)+b;
}
},
Elastic:{
easeIn:function(t,b,c,d,a,p){
if(t==0)returnb;
if((t/=d)==1)returnb+c;
if(!p)p=d*.3;
if(!a||a<Math.abs(c)){
a=c;
vars=p/4;
}elsevars=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)returnb;
if((t/=d)==1)returnb+c;
if(!p)p=d*.3;
if(!a||a<Math.abs(c)){
a=c;
vars=p/4;
}elsevars=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)returnb;
if((t/=d/2)==2)returnb+c;
if(!p)p=d*(.3*1.5);
if(!a||a<Math.abs(c)){
a=c;
vars=p/4;
}elsevars=p/(2*Math.PI)*Math.asin(c/a);
if(t<1)return-.5*(a*Math.pow(2,10*(t-=1))*Math.sin((t*d-s)*(2*Math.PI)/p))+b;
returna*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;
returnc*(t/=d)*t*((s+1)*t-s)+b;
},
easeOut:function(t,b,c,d,s){
if(s==undefined)s=1.70158;
returnc*((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)<1)returnc/2*(t*t*(((s*=(1.525))+1)*t-s))+b;
returnc/2*((t-=2)*t*(((s*=(1.525))+1)*t+s)+2)+b;
}
},
Bounce:{
easeIn:function(t,b,c,d){
returnc-Tween.Bounce.easeOut(d-t,0,c,d)+b;
},
easeOut:function(t,b,c,d){
if((t/=d)<(1/2.75)){
returnc*(7.5625*t*t)+b;
}elseif(t<(2/2.75)){
returnc*(7.5625*(t-=(1.5/2.75))*t+.75)+b;
}elseif(t<(2.5/2.75)){
returnc*(7.5625*(t-=(2.25/2.75))*t+.9375)+b;
}else{
returnc*(7.5625*(t-=(2.625/2.75))*t+.984375)+b;
}
},
easeInOut:function(t,b,c,d){
if(t<d/2)returnTween.Bounce.easeIn(t*2,0,c,d)*.5+b;
elsereturnTween.Bounce.easeOut(t*2-d,0,c,d)*.5+c*.5+b;
}
}
}
}
下面是个应用:
<body>
<!DOCTYPEHTML>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=gb2312">
<title>无标题文档</title>
<scriptsrc="util.js"type="text/javascript"></script>
<scriptsrc="animate.js"type="text/javascript"></script>
<styletype="text/css">
body{behavior:url("csshover.htc")}
*{padding:0;margin:0}
.mianbox{width:480px;margin:50pxauto;height:240px;}
.leftbtn{width:20px;background:#eee;border:1pxsolid#ddd;float:left;margin-right:8px;height:240px;}
.leftbtn:hover{background:#fff}
.rightbtn{width:20px;background:#eee;border:1pxsolid#ddd;float:right;height:240px;}
.rightbtn:hover{background:#fff}
.con{width:420px;float:left;height:240px;overflow:hidden;position:relative}
.conul{white-space:nowrap;font-size:0;position:absolute;left:0;top:0;}
.conli{display:inline;vertical-align:bottom;margin-right:10px}
</style>
</head>
<divclass="mianbox">
<divclass="leftbtn"id="leftbtn"></div>
<divclass="con">
<ul>
<li><imgsrc="http://pic25.nipic.com/20121121/2969675_091845785000_2.jpg"width="205"height="240"/></li>
<li><imgsrc="http://pic23.nipic.com/20120818/9715349_114354586392_2.jpg"width="205"height="240"/></li>
<li><imgsrc="http://pic20.nipic.com/20120329/9715349_154806479182_2.jpg"width="205"height="240"/></li>
<li><imgsrc="http://pic20.nipic.com/20120329/9715349_162301568121_2.jpg"width="205"height="240"/></li>
<li><imgsrc="http://pic23.nipic.com/20120824/9715349_160522342186_2.jpg"width="205"height="240"/></li>
<li><imgsrc="http://pic23.nipic.com/20120824/9715349_160651385195_2.jpg"width="205"height="240"/></li>
<li><imgsrc="http://pic20.nipic.com/20120329/9715349_163520278182_2.jpg"width="205"height="240"/></li>
<li><imgsrc="http://pic23.nipic.com/20120827/9715349_110350505124_2.jpg"width="205"height="240"/></li>
</ul>
</div>
<divclass="rightbtn"id="rightbtn"></div>
</div>
<script>
/**
*@paraobj 内容对象
*@paralbtn左按钮
*@pararbtn右按钮
*@paraw 每次滚动的宽
*@paraduration每次运行时间
*@paratween缓动类型
*/
functionscOnce(obj,lbtn,rbtn,w,autotime,duration,tween){
varam=newanimation(_ul),
step=0,
ulen=obj.scrollWidth,
timmerm
dr="left",
that=this;
//最右端?
functionisr(){
returnparseInt($util.dom.getStyle(obj,"left"))>=0;
}
//最左端?
functionisl(){
returnulen-Math.abs(parseInt($util.dom.getStyle(obj,"left")))-10<=w;
}
if(isr()&&isl())
return;
//左移
this.goleft=function(){
step+=-1*w;
am.go({left:step+"px"},duration,tween).start();
}
//右移
this.goright=function(){
step+=w;
am.go({left:step+"px"},duration,tween).start();
}
//注册左按钮事件
$util.evt.addEvent(lbtn,"click",function(){
isl()?that.goright():that.goleft();
})
//注册右按钮事件
$util.evt.addEvent(rbtn,"click",function(){
isr()?that.goleft():that.goright();
})
$util.evt.addEvent(rbtn,"mouseover",function(){
clearTimeout(timmer);
})
$util.evt.addEvent(lbtn,"mouseover",function(){
clearTimeout(timmer);
})
$util.evt.addEvent(rbtn,"mouseout",function(){
timmer=setInterval(auto,autotime);
})
$util.evt.addEvent(lbtn,"mouseout",function(){
timmer=setInterval(auto,autotime);
})
functionauto(){
if(isl()){
dr="right";
}
if(isr()){
dr="left";
}
that["go"+dr]();
}
timmer=setInterval(auto,autotime);
}
var_ul=document.getElementsByTagName("ul")[0],
lbtn=document.getElementById("leftbtn"),
rbtn=document.getElementById("rightbtn");
varstartgo=newscOnce(_ul,lbtn,rbtn,430,3000,500,$util.tween.Quint.easeInOut);
</script>
</body>
</html>相关文章