- 7 Tem 2013
- 8,189
- 641
Adding the HTML5 Canvas
[FONT="]
[/FONT][FONT="]
[FONT="]
[/FONT][FONT="]
[/FONT][FONT="]
[FONT="]
First, were going to need something to display the game. The HTML5 canvas element is essentially a sandbox of pixels that you can draw to dynamically. Were going to use a canvas to render the game, so we need to add it to our HTML page. Open default.html and replace Line 17 (the "Content goes here" line) with a canvas tag, so it looks like this:[/FONT]
[FONT="]Normally, youd specify width & height and add fallback content in case canvas isnt supported, but well set width/height later and we know canvas will be supported. However, this is just one of the many times you should consider coding practices in case you want to reuse some of your app code as a traditional web application but thats a story for another series of posts...[/FONT]
Making Things Easier with CreateJS[FONT="]
So how do we add things like our background and catapults? Unlike HTML content, canvas content is entirely created via JavaScript instructions. For the basics, read "How to draw on an HTML5 canvas" on MSDN.[/FONT]
[FONT="]Of course, we could use canvas methods to draw our game directly, but there are libraries of JavaScript out there to help, including ones well-suited to game development. CreateJS is a set of JavaScript libraries & tools, including EaselJS, PreloadJS, and others. Well use these in our game, so download EaselJS and PreloadJS, create a new folder for them as /js/CreateJS, and copy in the scripts (from the "lib" folders) as follows:[/FONT]
[FONT="]Adding the JavaScript files to the project isnt enough to use them, so reference them from default.html:[/FONT]
[FONT="]Tip: You can add script references by dragging the script from Solution Explorer onto the page. (Extra Tip: in HTML5, you don't need the type="text/javascript" script attribute anymore.)[/FONT]
[FONT="]Well use PreloadJS to help load assets before to use in the game and EaselJS to make it easier to manage the game loop and the drawing of image assets.[/FONT]