Wednesday, July 4, 2012

animateObjectFromTo

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 
  );
    /////////////////////////////////////////////////////////////////////////////////////////
// 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;
          console.log('top is now: ' + parseFloat(oCurrentStyle["top"]) + deltaYPerFrame + "px")
          setTimeout( function() { animate(); }, deltaTimePerFrame );
        }
      }