Search code examples
javascriptimageanimationsmoothing

javascript smooth animation from X,Y to X1,Y1


I'd like to sloothly move an image (or an element) from its actual X, Y location to X1, Y1.

When the distance between X and X1 is equal to that between Y and Y1 its easy. But what if the X difference is say 100px and Y diff is 273px?

Being new to Javascript, I don't want to re-invent the wheel! Besides, since I'm learning, I do NOT want to use jQuery or the likes. I want pure javascript.

Please supply with simple script :-)


Solution

  • One solution:

    function translate( elem, x, y ) {
        var left = parseInt( css( elem, 'left' ), 10 ),
            top = parseInt( css( elem, 'top' ), 10 ),
            dx = left - x,
            dy = top - y,
            i = 1,
            count = 20,
            delay = 20;
    
        function loop() {
            if ( i >= count ) { return; }
            i += 1;
            elem.style.left = ( left - ( dx * i / count ) ).toFixed( 0 ) + 'px';
            elem.style.top = ( top - ( dy * i / count ) ).toFixed( 0 ) + 'px';
            setTimeout( loop, delay );
        }
    
        loop();
    }
    
    function css( element, property ) {
        return window.getComputedStyle( element, null ).getPropertyValue( property );
    }
    

    Live demo: http://jsfiddle.net/qEVVT/1/