Coffeehouse Post

Single Post Permalink

View Thread: Do you have romnesia?
  • User profile image
    sysrpl

    @Bass: To animate all you do is repeatedly call setTimeout, then adjust styles based on an easing. A while back wrote a little easing browser for my own user defined easings (across multiple languages/platforms). Test page here.

    Generic Forum Image

    <!DOCTYPE HTML>
    <html>
    <body>
    <script type="text/javascript">
    // a few example easings
    
    function linear(percent) { return percent; }
    function easy(percent) { return percent * percent * (3.0 - 2.0 * percent); }
    
    var negcospi = 1.61803398874989;
    
    function snap(percent) {
        percent = percent * percent;
        percent = (percent * 1.4) - 0.2;
        return 0.5 - Math.cos(Math.PI * percent) / negcospi;
    }
    
    function time() {
      return new Date().getTime() / 1000;
    }
    
    // the animate routine
    
    function animate(element, easing, duration, onanimate, ondone, start) {
      start = start == null ? time() : start;
      window.setTimeout(function() {
        var percent = (time() - start) / duration;
        var done = percent >= 1.0;
        if (done) {
            onanimate(element, 1.0);
            if (ondone) {
                ondone(element);
            }
        } else {
            onanimate(element, easing(percent));
            animate(element, easing, duration, onanimate, ondone, start);
        }
      }, 5);
    }
    
    // our onanimate callback and a play function
    
    function move(element, percent) {
      element.style.left = 2000 * percent + "px";
    }
    
    function play() {
      animate(document.getElementById("red"), snap, 2.0, move);
    }
    </script>
    <div id="red" style="background: red; position: relative; width: 100px; height: 100px;"></div>
    <button onclick="play()">Play</button>
    </body>
    </html>