HTML5 introduced the canvas element which makes simple web based game creation a breeze. In this multi-part tutorial I am going to show you just how quickly you can get a basic pong game up and running using HTML5, JavaScript and CSS. All you will need is a browser that supports HTML5, a text editor and a bit of patience. In this first part we are going to set the stage of our game, in coming parts we will add movement, basic simulated AI and other finishing touches.
By the end of this tutorial you should have something that is similar to this – http://jsbin.com/ulowiy/3/
Image may be NSFW.
Clik here to view.
OK – Let’s get started.
The HTML
As I mentioned above, the backbone of the game will be the HTML5 canvas element which allows us to draw graphics on our webpage. As the name of the element suggests, it acts as our canvas to which we can add our graphics through JavaScript. The markup is very simple; all we need to do is give the element an id (so we can reference it from our code) and a width and height. Anything in-between the opening and closing tags will be displayed if your browser does not support the canvas element.
<canvas width="800" height="500"> Your browser does not support HTML5 </canvas>
Let’s also add a couple of divs into the body, one to display the scores and one to act as a container for everything.
<div id="container"> <div id="score"> You: <span id="playerScore">0</span> <span style="color: #6db33f;"><b>//</b></span> Computer: <span id="compScore">0</span> </div> <canvas width="800" height="500"> Your browser does not support HTML5 </canvas> </div>
To make things a little bit easier for us let’s use JQuery and one of Google’s hosted fonts by adding references to both in our document’s head.
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <link href="http://fonts.googleapis.com/css?family=Rambla:700" rel="stylesheet" type="text/css" />
This is all the HTML we need to set the stage for our game, the total complete markup should be similar to this:
<link href="http://fonts.googleapis.com/css?family=Rambla:700" rel="stylesheet"type="text/css" /> <script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <div id="container"> <div id="score"> You: <span id="playerScore">0</span> <span style="color: #6db33f;"><b>//</b></span> Computer: <span id="compScore">0</span> </div> <canvas width="800" height="500"> Your browser does not support HTML5 </canvas> </div>
The CSS
Now that we have our elements, let’s style them using some CSS. You can include the CSS in the HTML file as long as you place it in the document’s head and enclose it in style tags. The CSS is fairly self explanatory; we aren’t doing anything unusual so I won’t explain it in any great detail, although I have commented each block with a brief explanation.
<style type="text/css"> /*this block gives our canvas element a centered background image and a blue border*/ #pongGame { background:url(http://www.allstate.com/resources/Allstate/images/ni/NI-LinkedIn-Banner.jpg); background-size: 75%; background-repeat:no-repeat; background-position:center; border:1px solid #1666AF; } /*this block centers our container div so that it is positioned in the middle of our web page*/ #container { position: fixed; top: 50%; left: 50%; margin-left: -400px; margin-top: -275px; text-align: center; } /*this block sets the font attributes for our score div and gives it a blue border*/ #score { margin-left: 500px; font-family: 'Rambla', sans-serif; font-size:28px; color: #717073; border:2px solid #1666AF; margin-bottom: 5px; } /*this block sets the colour of the text within the playerScore span*/ #playerScore { color: #EE3424; } /*this block sets the colour of the text within the compScore span*/ #compScore { color: #EE8722; } </style>
The JavaScript
OK, let’s jump into the code that is going to draw the graphics onto our canvas element. Again this code can be placed in your HTML file as long as it contained within script tags and is placed in the head of the document. We are going to make use of JQuery’s $(document).ready function to ensure that all of our assets have fully loaded before executing. All of our code will be placed within this function.
We are going to need to define some global variables that we can access from anywhere in our code:
//global variables //stage var canvas; //this will be used to contain our canvas element var ctx; //this will be the context of our canvas element var WIDTH; //this will be the width of the canvas element var HEIGHT; //this will be the height of the canvas element //ball var x; //this will be the x position of the ball var y; //this will be the y position of the ball var ballRadius = 10; //this is the radius of the ball (pixels) //paddles var paddleHeight = 70; // this will be the height of the paddles (pixels) var paddleWidth = 10; //this will be the width of the paddles (pixels) var playerPaddle; //this will be the players paddle var playerPaddleColour = "#EE3424"; //this is the colour of the players paddle (red) var compPaddle;// this will be the computers paddle var compPaddleColour = "#EE8722"; //this is the colour of the computers paddle (orange)
Next we will need a function that will initialise our game for us; this function should only be called once, whenever the page is loaded for the first time. The purpose of this function is to assign values to some of the global variables we defined above.
function init() { //get the canvas element canvas = $('#pongGame')[0]; //get the context of that element ctx = canvas.getContext("2d"); //set our width and height variables equal to the width //and height of the canvas element WIDTH = canvas.width; HEIGHT = canvas.height; //set the starting height of the paddles to the center //of the y-axis playerPaddle = (HEIGHT / 2) - (paddleHeight/2); compPaddle = (HEIGHT / 2) - (paddleHeight/2); //set the x and y values for where the ball will start //in this case the center of the canvas x = 400; y = 250; //call the drawGame function drawGame(); }
The eagle eyed amongst you will have noticed we are calling a function called drawGame from within the init function. drawGame is a small function that will in fact call three other functions, one to draw the side lines, one to draw the ball and one to draw the paddles. For the purposes of the first part of the tutorial this function will only be called once, however once we get into movement in future parts of this tutorial the drawGame function will actually be called numerous times a second.
//This function draws the game stage function drawGame() { //draw the sidelines drawSideLines(); //draw the ball drawBall(); //draw the player paddle, passing variables defined above drawPaddle(0,playerPaddle,paddleWidth,paddleHeight,playerPaddleColour); //draw the comp paddle, passing variables defined above drawPaddle(WIDTH - 10,compPaddle,paddleWidth,paddleHeight,compPaddleColour); }
Firstly let us look at the drawSideLines function which, as the name suggests, will draw the sidelines of our pong game onto our canvas context.
//This function draws the side lines on the stage (roof and floor) function drawSideLines() { ctx.beginPath(); ctx.rect(0,0,WIDTH,15); ctx.closePath(); ctx.fillStyle="#1666AF"; ctx.fill(); ctx.beginPath(); ctx.rect(0,HEIGHT - 15,WIDTH,15); ctx.closePath(); ctx.fillStyle="#1666AF"; ctx.fill(); }
You can see that we are taking the canvas context element and drawing two blue rectangles onto our canvas. The .rect function takes 4 arguments; the first one is the x co-ordinate of where to start drawing, the second is the y co-ordinate of where to start drawing, the third is how many pixels wide to make the rectangle (in our case the width of the whole canvas) and finally the fourth is how many pixels in height to make the rectangle. The .fill function is the function that actually commits the graphic to the canvas.
The drawBall function is mostly similar, however this time we aren’t drawing a rectangle we are drawing a circle by using the .arc function. We are also going to make the ball green so that it stands out.
//this function draws the ball function drawBall() { ctx.beginPath(); ctx.arc(x, y, ballRadius, 0, Math.PI*2, true); ctx.closePath(); ctx.fillStyle="#6DB33F"; ctx.fill(); }
The .arc function takes 6 arguments; the first one is the x co-ordinate of where to start drawing, the second is the y co-ordinate of where to start drawing, the third one is the radius of the arc, the fourth is the start angle, fifth is the end angle (in our case a full circle) and lastly the sixth is a Boolean value to define whether or not to fill the arc.
The last function that we are going to define will handle the drawing of the paddles; you may have noticed that we called this function twice from the drawGame function (once for the player paddle and once for the computer paddle) but passing different parameters each time.
//this function draws a paddle function drawPaddle(xaxis,yaxis,pwidth,pheight,pcolour) { ctx.beginPath(); ctx.rect(xaxis,yaxis,pwidth,pheight); ctx.closePath(); ctx.fillStyle=pcolour; ctx.fill(); }
We use the .rect function again to draw our paddles onto the canvas and set them to the colours that we defined as global variables at the very beginning.
The last thing we need to do is call the init function to kick everything off, this should be the last line of code within your $(document).ready function.
//call the init function init();
And that’s it – If you want to see how that all fits together then take a look at the code here: http://jsbin.com/ulowiy/3/edit
Now that the stage is set we are ready to start adding movement to our game in the next part of the tutorial. I promise you that it will be a lot more rewarding than what was covered in this first part but it was necessary to get the foundations done first.
Mark
Tagged: Allstate NI, Allstate Northern Ireland, Belfast, Canvas, CSS, Game, HTML5, IT, JavaScript, JQuery, Mark B, Northern Ireland, Pong, Software Developer, Software Development Image may be NSFW.
Clik here to view.
Clik here to view.
