在Javascript中来回跟踪正弦波中的对象位置

时间:2017-10-11 12:10:07

标签: javascript html css

我在javascript中创建了程序,其中div在正弦波之后从左到右翻译它的位置。 这是代码:

<!DOCTYPE HTML>
    <head>
        <title>Move Object</title>
        <style>
            #field {position: relative;height: 300px;background-color: lightgreen;}
            #ball{ position: absolute;left: 0;bottom: 50%;width: 1em;height: 1em;border-radius: 0.5em;}
            #ball { background: red; }
        </style>
    </head>
    <body>     
        <div id="field">
            <div id="ball"></div>
            <script type="text/javascript">
                window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;

                var field = document.getElementById("field");
                var ball = document.getElementById("ball");
                var maxX = field.clientWidth - ball.offsetWidth;
                var maxY = field.clientHeight - ball.offsetHeight;
                var duration = 5; // seconds
                var gridSize = 50; // pixels
                var start = null;

                function step(timestamp){ 
                    var progress, x, y;
                    if(start === null) start = timestamp;
                    progress = (timestamp - start) / duration / 1000; // percent

                    x = progress * maxX/gridSize; // x = ƒ(t)
                    y = 2 * Math.sin(x); // y = ƒ(x)

                    ball.style.left  = Math.min(maxX, gridSize * x) + "px";
                    ball.style.bottom = maxY/2 + (gridSize * y) + "px";
                    if(progress >= 1) 
                    {   
                        start=null;
                    }
                    requestAnimationFrame(step);
                }
                requestAnimationFrame(step);
            </script>
        </div>
    </body>
</html>

该部门从左向右翻译,但我想追溯从右到左的动作。 谁能帮我解决这个问题?

先谢谢..

1 个答案:

答案 0 :(得分:1)

通过从函数域的最低成员到最高成员,以离散步骤迭代函数域。相反,从域的最后一个成员开始(你已经将其计算为mmayX)并从该离散步骤中减去它直到达到最低值。

如果这听起来很复杂,这里有一个可以更好地解释它的线性修复:

x =  maxX/gridSize - (progress * maxX/gridSize); 

改变这一点,瞧瞧:

demo fiddle of dot going backward