topical media & game development

talk show tell print

#javascript-code-08-sun.htm / htm



  <html>
  <head>
  <title>Canvas Sun Demo</title>
  <script>
  // Initalize the list of images that will be used
  var imgs = { sun: null, moon: null, earth: null };
  
  // Wait for the window to completely load
  window.onload = function() {
    // Load all the images from the document
    for ( var i in imgs )
      imgs[i] = document.getElementById(i);
  
    // Start drawing 10 times  per second
    setInterval( draw, 100 );
  };
  
  function draw() {
    // Get the time intervals that we need
    var time = new Date();
    var s = ( (2 * Math.PI) / 6) * time.getSeconds();
    var m = ( (2 * Math.PI) / 6000 ) * time.getMilliseconds();
  
    // Get the drawing context of the canvas
    var ctx = document.getElementById('canvas').getContext('2d');
  
    // Empty the canvas
    ctx.clearRect(0,0,300,300);
  
    // New items are always drawn under old items (used for the shadow)
    // More info: http://developer.mozilla.org/en/docs/Canvas_tutorial:Compositing
    ctx.globalCompositeOperation = 'destination-over';
  
    ctx.save();
      // Drawing at 0,0 = drawing at 150,150
      ctx.translate(150,150);
  
      // Rotate the canvas to earth's position
      ctx.rotate( (s + m) / 10 );
  
      // Move 105 pixels out
      ctx.translate(105,0);
  
      // The fill for the shadow (which will be
      // faded, so that we can see through it)
      ctx.fillStyle = 'rgba(0,0,0,0.4)';
      ctx.strokeStyle = 'rgba(0,153,255,0.4)';
  
      // Draw the shadow rectangle (its not perfect, but close)
      ctx.fillRect(0,-12,50,24);
  
      // Draw the earth
      ctx.drawImage(imgs.earth,-12,-12);
  
      ctx.save();
        // Rotate the canvas, relative to the rotation of the earth
        ctx.rotate( s + m );
  
        // Position the moon 'in orbit'
        ctx.translate(0,28.5);
  
        // Draw the moon image
        ctx.drawImage(imgs.moon,-3.5,-3.5);
      ctx.restore();
  
    ctx.restore();
  
    // Draw the earth's orbit  
    ctx.beginPath();
      ctx.arc(150,150,105,0,Math.PI*2,false);
    ctx.stroke();
  
    // Draw the static sun 
    ctx.drawImage(imgs.sun,0,0);
  }
  </script>
  </head>
  <body style="background:#000;">
    <canvas id="canvas" height="300" width="300"></canvas>
  
    <!-- Preload all our source images -->
    <div style="display:none;">
      <img src="sun.png" id="sun"/>
      <img src="moon.png" id="moon"/>
      <img src="earth.png" id="earth"/>
    </div>
  </body>
  </html>
  
  


(C) Æliens 20/2/2008

You may not copy or print any of this material without explicit permission of the author or the publisher. In case of other copyright issues, contact the author.