Thursday, October 20, 2011

Reaching for the Stars

While it is quite true that every journey in life begins with a single step, sometimes when you want to reach the stars...

Sorry, your browser does not support the canvas element, so you are not seeing the thing that's supposed to be here.

taking a second one can make all the difference.

Sorry, your browser does not support the canvas element, so you are not seeing the thing that's supposed to be here.
For posterity, here's the parallax star field code:
<html>
  <head>
  </head>
  <body>
    Hi! This is also a canvas:<br />
    <canvas id="canvas2" width="320" height="240">
    </canvas>
    <script type="text/javascript">
      var sf = {};//short for starfield, used as a namespace/pseudoclass.
      sf.numStars = 50;
      sf.brightStars = [];
      sf.midStars = [];
      sf.dimStars = [];
      sf.canvas = document.getElementById("canvas2");
      sf.context = sf.canvas.getContext("2d");

      sf.initStars = function(){
        var canvas = document.getElementById("canvas2");
        var i = 0;

        for (i=0; i<sf.numStars; i++){
          sf.brightStars[i] = {
            x: Math.floor(Math.random()*sf.canvas.width),
            y: Math.floor(Math.random()*sf.canvas.height)
          }
          sf.midStars[i] = {
            x: Math.floor(Math.random()*sf.canvas.width),
            y: Math.floor(Math.random()*sf.canvas.height)
          }
          sf.dimStars[i] = {
            x: Math.floor(Math.random()*sf.canvas.width),
            y: Math.floor(Math.random()*sf.canvas.height)
          }
        }
      }

      sf.moveStars = function(){
        var i = 0;

        for (i=0; i<sf.numStars; i++){
          sf.brightStars[i].x = (sf.brightStars[i].x + 4) % sf.canvas.width;
          sf.midStars[i].x = (sf.midStars[i].x + 2) % sf.canvas.width;
          sf.dimStars[i].x = (sf.dimStars[i].x + 1) % sf.canvas.width;
        }
      }

      sf.clearCanvas = function(){
        sf.context.fillStyle = "#000000";
        sf.context.fillRect(0, 0, sf.canvas.width, sf.canvas.height);
      }

      sf.drawStars = function(){
        var i = 0;

        //Draw the stars.
        sf.context.fillStyle = "#aaaaff";
        for (i=0; i<sf.numStars; i++){
          sf.context.fillRect(sf.brightStars[i].x, sf.brightStars[i].y, 1, 1);
        }
        sf.context.fillStyle = "#aaaaaa";
        for (i=0; i<sf.numStars; i++){
          sf.context.fillRect(sf.midStars[i].x, sf.midStars[i].y, 1, 1);
        }
        sf.context.fillStyle = "#aa7777";
        for (i=0; i<sf.numStars; i++){
          sf.context.fillRect(sf.dimStars[i].x, sf.dimStars[i].y, 1, 1);
        }
      }

      sf.drawFrame = function(){
        sf.clearCanvas();
        sf.drawStars();
        sf.moveStars();
        setTimeout(sf.drawFrame, 60);
      }

      sf.initStars();
      sf.drawFrame();
      //setInterval(sf.drawFrame, 250);
    </script>
  </body>
</html>

No comments: