javascriptjqueryhtmljquery-animatecurve

.animate with a curve


First take a look:

enter image description here

The cat needs to move to the x in a curve. (see the arrow)

When the cat hits the x, it should stay 10 seconds, and after that the cat should go back to o, again in a curve, and repeat.

I tried it with this code:

function curve() {
    $('#cat').delay(10000).animate({top: '-=20',left: '-=20'}, 500, function() {
        $('#cat').delay(10000).animate({top: '+=20', left: '+=20'}, 500, function() {
            curve();
        });
    });
}

curve();

But the cat is moving like this:

enter image description here

Is there a way to get the cat to move in this kind of curve?


Solution

  • You can use easing to achieve that, by doing a compound movement :

    function curve () {
        $('#cat').delay(10000).animate({top: "+=20px", left: "+=20px"}, {
          duration: 500, 
          specialEasing: {top: 'easeOutQuad', left: 'easeInQuad'}, 
          complete: function () { 
            $('#cat').animate({top: "-=20px", left: "+=20px"}, {
              duration: 500, 
              specialEasing: {top: 'easeInQuad', left: 'easeOutQuad'},
              complete: function() {
                // repeat the other way around.
              }});
          }
        });
    }
    

    It works since jQuery 1.4, according to jQuery docs and the easings mentionned require jQuery UI (but only the Effect Core module). Each .animate() call accounts for a quarter of a full circle path, and the reverse easeInQuad vs. easeOutQuad makes the path looks like a circular path instead of straight to the new position.