WEBDOOD.COM

Javascript animateObjectFromTo

by webdood on Jul.04, 2012, under Javascript, Objects, Software Development

This method will animate an object from a given left, top to another left, top over a specified number of milliseconds at a specified frame rate.

This is an example of how it might be called:

  var myDiv = document.getElementById('myDiv),
      currentPosition = window.getComputedStyle(myDiv,null),
      currentLeft     = parseFloat(currentPosition["left"]),
      currentTop      = parseFloat(currentPosition["top"]);
  animateObjectFromTo(
    myDiv,
    { top:currentTop, left:currentLeft },
    { top:0, left:currentLeft },
    250
  );

Notice how the method uses an inner function for the animation heavy lifting.

///////////////////////////////////////////////////////////////////////////////////////////
//  animateObjectFromTo([object|string] oHTMLElement, json From, json To, int totalTimeInMilliseconds, OPTIONAL int framesPerSecond)
//   Sets up an animation that interpolates frame animation from a beginning top, left coordinate
//   to an ending top, left coordinate over a number of milliseconds at a specified frame rate
//      totalTimeInMilliseconds - default is 1 second
//      framesPerSecond - default is 30
/////////////////////////////////////////////////////////////////////////////////////////
    animateObjectFromTo : function(oHTMLElement, from, to, totalTimeInMilliseconds, framesPerSecond) {
      if (typeof(oHTMLElement)=="string")  {
        oHTMLElement = document.getElementById(oHTMLElement);
      }
      totalTimeInMilliseconds = totalTimeInMilliseconds || 1000;
      framesPerSecond = framesPerSecond || 30;
      var currentFrame      = 0,
          numberOfFrames    = parseInt(totalTimeInMilliseconds / framesPerSecond),
          deltaTimePerFrame = totalTimeInMilliseconds/numberOfFrames,
          deltaXPerFrame    = (to.left - from.left)/numberOfFrames || 0,
          deltaYPerFrame    = (to.top - from.top)/numberOfFrames || 0;

      animate();

      function animate() {
        if (currentFrame<numberOfFrames) {
          var oCurrentStyle = document.defaultView.getComputedStyle(oHTMLElement, null);
          oHTMLElement.style.left = parseFloat(oCurrentStyle["left"]) + deltaXPerFrame + "px";
          oHTMLElement.style.top  = parseFloat(oCurrentStyle["top"]) + deltaYPerFrame + "px";
          currentFrame += 1;
          setTimeout( function() { animate(); }, deltaTimePerFrame );
        }
      }

shannon norrell


Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Blogroll

A few highly recommended websites...

  • A List Apart
  • Dive into HTML5
  • Javascript: The Good Parts
  • QuirksMode.org