4umi.com/web/javascript/moon

The moon today

Beautiful Javascript

A clever trick to write circles combined with some even more clever, not to say beautiful date calculations produces this not perfect but still amazingly accurate picture of the current moon phase, based on the local time as read from your system's clock. See the script. In addition, if the plug-in SMELL.DLL is installed, your computer should now be generating the scent of roses. Some appropriate romantic music may also be appreciated. Or would you prefer waiting for the sun?

The moon

See the moon for yesterday, today, tomorrow, next week, two or three weeks from now, or .

The script

Syntax highlight the code.

// original: James Thiele, www.eskimo.com/~jet/javascript/

function moonphase( date ) {
 date.setTime( date.getTime() + date.getTimezoneOffset() * 60000 );
 var black = '/black.gif', white = '/image/white.gif',
  i, m, size = moonsize.options[moonsize.selectedIndex].value, width,
  a = [ '<p>This is the moon on ' + formatdate( date ) + ':<\/p><p class="moon">' ],
  bluemoon = new Date( 96, 1, 3, 16, 15, 0 ),
  lunarperiod = 29 * ( 24 * 3600 * 1000 ) + 12 * ( 3600 * 1000 ) + 44.05 * ( 60 * 1000 ),
  phasetime = ( date.getTime() - bluemoon.getTime() ) % lunarperiod,
  fullmoon = Math.round( ( lunarperiod - phasetime ) / ( 24 * 3600 * 1000 ) ),
  fraction = phasetime / lunarperiod,
  left  = fraction >= 0.5 ? black : white,
  right = fraction >= 0.5 ? white : black,
  percent = Math.round( 200 * fraction ) % 100;

 for( i = -(size-1); i < size; ++i ) {
  width = 2 * parseFloat( Math.sqrt( size * size - i * i ) ) / 100;
  if( percent!==100 ) {
   a.push( '<img src="' + left + '" width="' + Math.round( width * ( 100 - percent ) ) + '" height="1"/>' );
  }
  if( percent!==0 ) {
   a.push( '<img src="' + right + '" width="' + Math.round( width * percent ) + '" height="1"/>' );
  }
  a.push( '<br>' );
 }

 a.push( '<\/p><p>' +
  ( fullmoon===0 ? 'It is full moon..' :
   ( fullmoon===1 ? 'Tomorrow is the next full moon' :
    'The next full moon will be in ' + fullmoon + ' days time' ) ) + '.<\/p>' );

 gid( 'moon' ).innerHTML = a.join( '' );
}

function moonloop( n ) {
 if( moonanim.checked ) {
  var t = new Date(); t.setTime( today.getTime() + 86400000 * n );
  moonphase( t );
  window.setTimeout( 'moonloop(' + (++n) + ');', 10 );
 }
}

moonphase( new Date() );

Reference