day47—JavaScript运动的停止条件

转行学开发,代码100天——2018-05-02

前面学过了JavaScript运动的两种常用情形:匀速运动与缓冲运动。在这两种运动的处理过程中最大的区别在于速度的处理和到达目标点的处理。

即本文需要学习和记录的JavaScript运动的停止条件问题。

1.匀速运动的停止条件

匀速运动框架:

var timer = null;
        function startMove(iTarget)
        {
            var oDiv = document.getElementById("div1");
            clearInterval(timer);
            var speed=0;

            timer = setInterval(function(){
                if (oDiv.offsetLeft<iTarget) {
                    speed = 7;
                }else
                {
                    speed=-7;
                }
                oDiv.style.left = oDiv.offsetLeft+speed+"px";
            },300);
        }

假设让图中红色物体匀速移动到左100位置和左300位置。

<input id="btn1" type="button" value="到100" onclick="startMove(100);">
<input id="btn2" type="button" value="到300" onclick="startMove(300);">
<div id="div1">    </div>
<div id="div2">    </div>
<div id="div3">    </div>
    <style type="text/css">
    #div1{width: 100px;height: 100px ;position: absolute;top: 50px;left: 400px;background: red;}
    #div2{width: 1px;height: 100px ;position: absolute;top: 50px;left: 100px;background: black;}
    #div3{width: 1px;height: 100px ;position: absolute;top: 50px;left: 300px;background: black;}
    </style>

执行后发现物体在目标点位置附近来回移动,无法停止。

究其原因,可以发现加上速度±7之后,使物体总是在目标点附近,多一步就超了,少一步就不足。

这时,按照绝对要求是没法很好解决的。因此我们采用一个折中的办法。即在目标点附近,可以默认到达。

这时我们就需要一个在目标位置附近的判断,用到一个数学中的绝对值方法,Math.abs();

 完善后的匀速运动框架:

var timer = null;
        function startMove(iTarget)
        {
            var oDiv = document.getElementById("div1");
            clearInterval(timer);
            var speed=0;

            timer = setInterval(function(){
                if (oDiv.offsetLeft<iTarget) {
                    speed = 7;
                }else
                {
                    speed=-7;
                }
                if (Math.abs(oDiv.offsetLeft-iTarget)<=7) {
                    oDiv.style.left = iTarget+"px";
                }else
                {
                   oDiv.style.left = oDiv.offsetLeft+speed+"px";
                }
            },300);
        }

执行后发现,基本达到预期效果(肉眼看不出的小处理效果)

                 

 2.缓冲运动的停止条件

在缓冲运动中,由于速度变化可调,只需要物体缓冲运动的最终位置为目标位置即可停止。

正常执行缓冲运动框架即可。这里需要特别注意以下几点:

1>速度必须取整,方法是Math.ceil()向上取整;Math.floor()向下取整。

2>目标点必须是整像素点。方法是parseInt();

猜你喜欢

转载自www.cnblogs.com/allencxw/p/8983182.html
今日推荐