美文网首页
11js动画模拟一个小球的自由落体运动

11js动画模拟一个小球的自由落体运动

作者: An的杂货铺 | 来源:发表于2019-03-13 10:50 被阅读0次
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
        <style>
             * {
                 padding: 0;
                 margin: 0;
             }
    
             div {
                 width: 28px;
                 height: 28px;
                 border-radius: 50%;
                 background-color: red;
                 position: absolute;
                 left: 0;
                 top: 200px;
                 background:url(ball.jpg) no-repeat center center;
                 background-size:100% 100%;
             }
        </style>
    </head>
    <body>
        <button id="fly">Flying</button>
        <div id="ball"></div>
        <script>
            function $(id){
                return document.getElementById(id);
            }
            var speedX = 6,speedY = -16;
            var ball = $('ball');
            var totalH = window.innerHeight;
            var totalW = window.innerWidth;
            var fly = $('fly');
            fly.onclick = function(){
                clearInterval(timer);
                var timer = setInterval(function(){
                    ball.style.top = ball.offsetTop + speedY + 'px';
                    ball.style.left = ball.offsetLeft + speedX + 'px';
                    var maxH = totalH - ball.offsetHeight;
                    var maxW = totalW - ball.offsetWidth;
                    if(ball.offsetTop>=maxH){
                        ball.style.top = maxH+'px';
                       
                        speedY*=-0.9;
                        speedX--;
                        if(speedX<=0){
                            speedX = 0;
                        }
                        if(Math.abs(speedY)<=1){
                            ball.style.top = maxH+'px';
                            console.log(speedY)
                            clearInterval(timer);
                        }
                    }
                    speedY++;
                },20)
            }
        </script>
    </body>
    </html>
    

    如下图


    three.gif

    相关文章

      网友评论

          本文标题:11js动画模拟一个小球的自由落体运动

          本文链接:https://www.haomeiwen.com/subject/yphzpqtx.html