开发者

Moving a picture around slowly

I have a picture of an Air balloon. I need it to fly around my page randomly (it is kind of small). I need it only to fly in the top half of my page. I found the following code:

$("#Friends").animate({ 
        top: "-=30px",
      }, duration );

But I'm not sure how I could loop it and have it go both on the x axis and the y axis. Thanks if you can! I do have jQu开发者_开发技巧ery enabled :)


How about something like this.... LIVE FIDDLE

HTML

<img src="http://www.birdsnways.com/imgs/blbd48rt.gif" id="picture" />

CSS

#picture{
    position:absolute;   
}

JS

doNextPoint();

function doNextPoint(){

    var maxX = $(window).width() - $('#picture').width();    
    var newX = rand(0, maxX);    
    var maxY = ($(window).height()/2) - $('#picture').height();
    var newY = rand(0, maxY);
    var speed  = rand (1000, 3000);

    $('#picture').animate({
        'top': newY + 'px',
        'left': newX + 'px' 
    }, speed, function(){
        doNextPoint();    
    });
}


function rand (min, max) {
     return Math.floor(Math.random() * (max - min + 1)) + min;
}


CSS

#friends { position: absolute; }

Markup

<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();
});

Live demo: http://jsfiddle.net/W69s6/embedded/result/

More updated Live Demo: http://jsfiddle.net/9cN4C/

(old demo is obsolete and has a broken link, however the code is still correct so it is left for reference, not for demonstration)


You can stick that code into a named function, and then add that function as the callback parameter for the animation, so it will call itself again after it finishes.

var flying;
flying = function() {
    $("#Friends").animate({ 
        top: "-=30px",   // you'll need to change this
      },
      duration,
      flying
    );
}
flying();

As is, it will just keep flying upward because the animation is always set to go up by 30 px. You'll have to change the flying function to randomize the motions a bit. For more realism, save the previous movement, and just change it by a little (small acceleration) so it doesn't have very jerky motions.


To loop it: use SetTimeout: https://developer.mozilla.org/en/window.setTimeout

For the x-axis, use the CSS property left: (top: will get you y-axis)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜