Adventures in TypeScript 01

It has been a while, but I’m back with a new set of tutorials. I have ventured off and started to learn TypeScript, so I decided I should write up what I have done. For the first part of this adventure, I’m going to take you thru the adventure of creating a Breakout clone using a canvas. Let’s begin this adventure!

Index.html – The Starting Point

First off, let’s start by creating a new html file to house the canvas. All we need is a canvas with an id of “gameCanvas”. To make the game line up correctly inside the canvas, make sure it is has a width of 480 pixels and a height of 320 pixels. Below is how I laid my html page.

Pretty simple little file. If you load it up, you should have a nice little grey rectangle on the page.

Game.ts – The Guts of The Game

Now we have the basic html page to hold our canvas, lets create the TypeScript file that will house the guts of the game. I chose to name it game.ts, but you can name it whatever you want. The first thing we want to do is create a couple of variables that house the canvas and the rendering context.

var canvas: HTMLCanvasElement;
var ctx: CanvasRenderingContext2D;

Since this is TypeScript, we are giving both of the variables a definite type. Now we need to actually grab the canvas from the html. To do this, we will grab it using the window.onload event.

The call to requestAnimationFrame(gameLoop) tells the browser that we want to call the function gameLoop right before you repaint the screen. The next 2 statements are just filling the whole canvas to black. To see this in action, we need to place the call to gameLoop at the bottom of the window.onload event we created earlier.

Now to compile the TypeScript and then add the newly created .js file to the HTML file we created at the very beginning. Once you get all that done, you can load up the HTML file, and the grey rectangle should now be black.