本文實例講述了JS實現勻加速與勻減速運動的方法。分享給大家供大家參考,具體如下:
/* * 動畫幀函數 * * */ var requestFrame=function(){ var prefixList=['webkit','moz','ms']; var func; for(var i=0;i<prefixList.length;i++){ func=window[prefixList[i]+"RequestAnimationFrame"]; if(func){ return function(callback){ func(callback); } } } return function(callback){ setTimeout(callback,67); }}();/* * 勻加速運動 * * */function animate_easeIn(element,from,to,duration,callback){ var time=+new Date; var distance=to-from; var a=2*distance/(duration*duration); //加速度a=2x/t^2(包含方向) var func=function(){ var time2,offsetDis,durTime; time2=+new Date; durTime=time2-time; //運動的時間間隔 offsetDis=Math.ceil(a*durTime*durTime/2);//X=a*t^2/2 if(duration<durTime){ element.css('left',to+'px'); callback(); }else{ element.css('left',from+offsetDis+'px'); requestFrame(func); } } func();}/* * 勻減速運動 * * */function animate_easeOut(element,from,to,duration,callback){ var time=+new Date; var distance=Math.abs(to-from); var a=2*distance/(duration*duration); //x=a*t^2/2 求出加速度 var v0=Math.sqrt(distance*2*a); // 根據公式:2as=v^2求出初速度 var func=function(){ var time2,offsetDis,durTime,pos; time2=+new Date; durTime=time2-time; offsetDis=Math.ceil(v0*durTime-a*durTime*durTime/2); //根據s=v0*t+1/2*a*t^2求出位移x if(duration<durTime){ element.css('left',to+'px'); callback(); }else{ pos=from>to? from-offsetDis : from+offsetDis; element.css('left',pos+'px'); requestFrame(func); } } func();}
希望本文所述對大家JavaScript程序設計有所幫助。
新聞熱點
疑難解答