如何使用jquery使图像在圆形路径中移动?

时间:2012-05-11 12:31:55

标签: jquery

这里我试图让图像在圆形路径中移动,但它不是在圆形路径中移动..我试过这样Moving a picture around slowly

CSS

#friends { position: absolute; }

标记

<img src="http://jsfiddle.net/img/logo.png" 
id="friends"/>

JS

function moveit() {

    var newTop = Math.floor(Math.random()*350);
    var newLeft = Math.floor(Math.random()*1024);
    var newDuration = Math.floor(Math.random()*5000);

    $('#friends').animate({
      top: newTop,
      left: newLeft,
      }, newDuration, function() {
        moveit();
      });

}

$(document).ready(function() {
    moveit();
});

现场演示:http://jsfiddle.net/W69s6/embedded/result/

任何建议??

3 个答案:

答案 0 :(得分:11)

另一种变体(基于Div Moving in cycle rotation using Javascript):

var t = 0;

function moveit() {
    t += 0.05;

    var r = 100;         // radius
    var xcenter = 100;   // center X position
    var ycenter = 100;   // center Y position

    var newLeft = Math.floor(xcenter + (r * Math.cos(t)));
    var newTop = Math.floor(ycenter + (r * Math.sin(t)));

    $('#friends').animate({
        top: newTop,
        left: newLeft,
    }, 1, function() {
        moveit();
    });
}

$(document).ready(function() {
    moveit();
});​

DEMO: http://jsfiddle.net/W69s6/20/

答案 1 :(得分:3)

看一下这个很棒的插件jQuery.path:)

答案 2 :(得分:3)

使用Animate:

尝试此操作
function animateCircle(id, speed, radius, startx, starty, phi) {  
    if (!phi) { phi = 0 };
    var int = 2 * (Math.PI) / speed;
    phi = (phi >= 2 * (Math.PI)) ? 0 : (phi + int);
    var $m = startx - radius * Math.cos(phi);
    var $n = starty - radius * Math.sin(phi);

    $("#friends").animate({
        marginLeft: $m + 'px',
        marginTop: $n + 'px'
      }, 1, function() { 
             animateCircle.call(this, id, speed, radius, startx, starty, phi) 
          }
    );

};

您可以像这样调用任何div的函数:

animateCircle('#friends', 100, 100, 400, 250);

DEMO http://jsfiddle.net/W69s6/18/

DEMO 2 http://jsfiddle.net/W69s6/34/

改编自here