0

我正在尝试使图像向后移动 360°(不旋转),但到目前为止,我只能向特定方向移动,如果我添加左侧和底部路线,那么图像将斜向左侧和底部。以下是属性:

CSS

#circle{
    background:red; 
    border-radius:100px; 
    height:100px; width:100px; 
    position:absolute;
}

Java脚本

(function() {

var speed = 10, 

  moveBox = function(){
  var el = document.getElementById("circle"),
        left = el.offsetLeft,
        moveBy = 3;     

    el.style.left = left + moveBy + "px";

        if(left > 200){
            clearTimeout(timer);
        }
    };

    var timer = setInterval(moveBox, speed);

}());

HTML:

<div id='circle'></div>

JsFiddle在线演示

问题是循环回红色圆圈,我希望它以循环方式移动到左 > 下 > 右 > 上。

谢谢您的帮助。

4

1 回答 1

4

使用 Math.sin 和 Math.cos 来描述圆:http: //jsfiddle.net/E3peq/7/

(function() {
    var speed = 10, 
        moveX = 0.1,
        moveY = 0.1,
        increment = 0.1,
        amp = 10,
        moveBox = function(){
            var el = document.getElementById("circle"),
                left = el.offsetLeft,
                top = el.offsetTop;

            moveX += increment;
            moveY += increment;

            var moveXBy = Math.cos(moveX) * amp;
            var moveYBy = Math.sin(moveY) * amp;

            el.style.left = (left + moveXBy) + "px";
            el.style.top = (top + moveYBy) + "px";

            if(left > 200){
                clearTimeout(timer);
            }
        };

        var timer = setInterval(moveBox, speed);

}());

编辑:亚伯拉罕在评论中的回答实际上比这更好看......

于 2013-11-11T17:48:03.113 回答