全国统一服务热线:400-633-9193

JS实现的抛物线运动效果示例

    网络     2018-02-13    2654

本文实例讲述了JS实现的抛物线运动效果。分享给大家供大家参考,具体如下:

先来看看运行效果:

具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<!doctype html >
<html>
<head>
  <meta charset="utf-8"/>
  <title>抛物线运动</title>
  <style>
    .pwx_rect{position:absolute;left:10px;top:300px;background-color:#888;height:50px;width:50px;}
    .pwx_hr{border-top:2px solid #ddd;position:absolute;width:98%;left:0px;top:350px;}
  </style>
  <script>
    test = function(){
      var rect = document.getElementById("rect");
      pwx(rect,60,5); //参数2:抛物线角度,参数3:横向速度每次增加5
    }
    function pwx(rect,radian,step){
      var animate = function(opt){
        var cos = Math.cos(opt.radian*Math.PI/180);//邻边比斜边,60度的话等于1/2
        var sin = Math.sin(opt.radian*Math.PI/180);//对边比斜边,30度的话等于1/2
        var left = opt.rect.offsetLeft;
        var top = opt.rect.offsetTop;
        if(opt.radian>0){
          left+=opt.step;
          opt.radian-=1; //角度递减1
          var a = left - opt.initLeft;
          var c = (a/cos);
          var b = (sin*c);
          opt.rect.style.left = opt.initLeft+a+"px";
          opt.rect.style.top = opt.initTop-b+"px";
          setTimeout(function(){
            animate(opt);
          },10);
        }else{
          opt.rect.style.left = left+opt.step+"px";
          opt.rect.style.top = opt.initTop+"px";
        }
      }
      animate({
        step : step,
        rect : rect,
        radian : radian,
        initTop : rect.offsetTop,
        initLeft : rect.offsetLeft
      });
    }
  </script>
</head>
<body>
www.jb51.net
<input type="button" value="抛物线" onclick="test()"/>
  <div class="pwx_rect" id="rect"></div>
  <div class="pwx_hr"></div>
</body>
</html>

实现思路:

X方向的边长每次递增5,角度每次递减1,根据这两个已知条件,通过三角函数就可以计算出Y方向的长度是多少

从而得出每次运动的X和Y方向的坐标值,达到抛物线的效果


  分享到:  
0.2485s