Home >Web Front-end >JS Tutorial >How to implement buffering motion in js (code example)

How to implement buffering motion in js (code example)

不言
不言Original
2018-08-31 10:25:001240browse

The content of this article is about how to implement buffering movement in js (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Characteristics of buffering motion

  • Gradually slows down and finally stops

  • The farther the distance, the greater the speed

  • The speed is determined by the distance

  • Speed ​​= (target value-current value)/scaling factor

The distance is large and the speed is large.
The distance is small and the speed is small.
Speed ​​is directly proportional to distance.
The speed must be rounded during buffering motion. If the speed is 0.9, it will directly become 0 without rounding; if the speed is greater than 0, it should be rounded up, and if it is less than 0, it should be rounded down.
Next we will make a buffering movement for a div to move from 0 to 300, and a buffering movement for a div to move from 600 to 300.

Code to implement buffering motion

<!DOCTYPE html>
<html>
  <head>
    <title>缓冲运动</title>
    <style>
      #div1{
        width: 100px;
        height: 100px;
        background: red;
        position: absolute;
        /* left: 0; */
        left: 600px;
        top: 50px;
      }
      #div2{
        /* 300位置的参考线 */
        width: 1px;
        height: 300px;
        position: absolute;
        left: 300px;
        top: 0;
        background: #000;
      }
    </style>
    <script>
      window.onload=function(){
        var oBtn=document.getElementById("btn1");
        oBtn.onclick=function(){
          startMove();
        }
      }

      function startMove(){
        var oDiv=document.getElementById("div1");
        setInterval(function(){
          var speed=(300-oDiv.offsetLeft)/10;
          speed=speed>0?Math.ceil(speed):Math.floor(speed);//取整
          oDiv.style.left=oDiv.offsetLeft+speed+"px";
        },30);
      }
    </script>
  </head>
  <body>
    <input id="btn1" type="button" value="开始运动" />
    <div id="div1"></div>
    <div id="div2"></div>
  </body>
</html>

Related recommendations:

How to use the encapsulation function of JS motion buffering effect

JS implementation of multi-object buffer motion example code_javascript skills

The above is the detailed content of How to implement buffering motion in js (code example). 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