A friend of mine from the Java world has been trying to get into JS lately.
He understood the basics of how JS works – Functions look (on the outside) superficially similar to Java, it has standard loops/variables, etc.
Canvas functions are very straight forward- The part that confused him was “How do I create a game loop”, and “How do I update the page based on JSON responses from my server?”
We’ll start with our very simple HTML page.
Anyone who’s done even “Hello World” should understand most of what we’re doing here.
We’re loading our JS, then three divs – Header, Game, and Footer.
<html> <head> <title>This is an example</title> <!-- Include are our JS scripts. The "defer" line just tells it to run this after the page loads. It's not actually needed, but it makes the initial load faster We're loading in jQuery via a CDN, but copying it locally would work just as well. This is just one less file to deal with. --> <script defer src="http://code.jquery.com/jquery.js"></script> <script defer src="exampleCode.js"></script> </head> <!-- In the body (below), define the game however you want it to look. I'm using 3 divs, just for the sake of showing we're only showing/changing the game div. There's nothing special about this setup. --> <body> <div id="Intro"> This is the beginning of the game. </div> <div id="Game"> The GAME GOES HERE. </div> <div id="Footer"> This is the bottom. </div> </body>
Now this is calling our JS, exampleCode.js –
That’s also very simple. We’re just going to do two “game loops” to update the page.
One of which updates the color, and the other uses an AJAX request
This is equal to " + hours + ":" + minutes + ":" + seconds; // This redefines the HTML inside the game object to whatever we pass it. In this case, it's the time. // Get the Game's DOM object // This gets the instance of the Game, just like we were in the first function. game = $("#Game"); // Replace the Game's HTML. // Just like used the background function in the first example (above), here we're overwriting the HTML that's in the Game object. // Everytime this runs, everthing that is in the game div is erased, and replaced with whatever string we pass. // In this case, we're passing in our two time-based strings we just created. game.html(timeStampString + formattedTime); } // Run the code above, every 500ms self.setInterval("ChangeColor()",500); self.setInterval("UpdateTime()",1000);
You can see this in action at jsfiddle.
It’s all very very straightforward code, but it occured to me that it might be useful to others, so I’ve archived it here for anyone who finds it 😉