Moving an image with 360° angle in Javascript

早过忘川 提交于 2019-12-12 05:55:34

问题


I am trying to make an image move 360° (not rotate) back it's course, but so far I was able to move only to a specific direction, if I add left & bottom course, then the image going diagonal to left & bottom. Here are the properties:

CSS

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

JavaSript

(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 Online Demo

The problem is looping back the red circle, I want it to move to left > bottom > right > up in a circular manner.

thanks for the help.


回答1:


Using Math.sin and Math.cos to describe the circle: 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);

}());

Edit: Abraham's answer in the comments is actually a lot nicer looking than this...



来源:https://stackoverflow.com/questions/19912069/moving-an-image-with-360-angle-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!