Building A Great DHTML Chaser - DHTML Lab | 7 | WebReference

Building A Great DHTML Chaser - DHTML Lab | 7

Logo

DHTML in GreatEqualizer.com, I:
Building A Great DHTML Chaser



We've got our algorithm for smooth animation on any platform. We've got our algorithm for sine wave deceleration. We're ready to build our super chaser. Here's how I did it:

<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
// The chaser object. Since we don't anticipate having more
// than one on a page, we don't bother making this into
// a class definition. All necessary properties are set as
// properties of this object to avoid global variables.
var oChaser = {
    topMargin  : 25,
    callRate   : 35,
    ceiling    : 55,
    slideTime  : 1200,
    isIE       : document.all ? true : false,
    chaserDiv  : document.all ? document.all.chaser : document.chaser
}

// Arrange to have the main loop called as often as possible, 
// but not more often than every 35 milliseconds.
// Even though some OS's can achieve better than that,
// there's no real reason to
// overload them if its not going to improve
// the animation quality very much.
// I tested, and better than 35ms doesn't do very much visually.
window.setInterval("oChaser.main( )", oChaser.callRate)
// Main loop. Updates targetY, and decides whether to start
// the animation over again, continue an existing animation,
// or do nothing at all.
oChaser.main = function( )
{
    this.currentY   = this.isIE ? this.chaserDiv.style.pixelTop : this.chaserDiv.top
    this.scrollTop  = this.isIE ? document.body.scrollTop : window.pageYOffset
    var newTargetY  = Math.max( this.scrollTop + this.topMargin, this.ceiling )
    
    if ( this.currentY != newTargetY ) {
        if ( newTargetY != this.targetY ) {
            this.targetY = newTargetY
            this.slideInit( )
    
        }
        this.slide( )
        
    }
}
// .slideInit( ). Initializes the slide animation. Sets properties
// of the oChaser object that will represent the various paramaters
// for the sine wave function.
oChaser.slideInit = function( )
{
    var now    = new Date( )
    
    this.A     = this.targetY - this.currentY
    this.B     = Math.PI / ( 2 * this.slideTime )
    this.C     = now.getTime( )
    this.D     = this.currentY
}

// .slide( ). Moves the oChaser one frame. Its rate decreases and
// is defined by a sine wave.
oChaser.slide = function( )
{
    var now   = new Date( )
    var newY  = this.A * Math.sin( this.B * ( now.getTime( ) - this.C ) ) + this.D
    newY      = Math.round( newY )
    if ( ( this.A > 0 && newY > this.currentY ) ||
         ( this.A 
      

Here's a sample file that demonstrates the new, improved sine wave animation: complex_chaser.html.

Now there's just one small problem left.


Produced by Aaron Boodman and

All Rights Reserved. Legal Notices.
Revised: Sept 19, 2000

URL: https://www.webreference.com/dhtml/column37/7.html