Home  >  Article  >  Web Front-end  >  Code sharing for realizing uniform acceleration and uniform deceleration motion using JS

Code sharing for realizing uniform acceleration and uniform deceleration motion using JS

巴扎黑
巴扎黑Original
2017-09-05 09:45:162204browse

This article mainly introduces the method of realizing uniform acceleration and uniform deceleration in JS, and involves related implementation techniques of JavaScript combining time functions and mathematical operations to dynamically operate page element styles. Friends who need it can refer to it

The example in this article describes the method of realizing uniform acceleration and uniform deceleration in JS. Share it with everyone for your reference, the details are as follows:


/*
 * 动画帧函数
 *
 * */
  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(&#39;left&#39;,to+&#39;px&#39;);
      callback();
    }else{
      element.css(&#39;left&#39;,from+offsetDis+&#39;px&#39;);
      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(&#39;left&#39;,to+&#39;px&#39;);
      callback();
    }else{
      pos=from>to? from-offsetDis : from+offsetDis;
      element.css(&#39;left&#39;,pos+&#39;px&#39;);
      requestFrame(func);
    }
    }
    func();
}

The above is the detailed content of Code sharing for realizing uniform acceleration and uniform deceleration motion using JS. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn