How to Create the Canvas Tag for Your HTML5 Browser Game

0
7

If you want to create a HTML5 browser game, the first thing you need to do is add the canvas to your webpage. If you already know HTML then this should be fairly easy for you. However, adding the canvas tag is only the very first step. After all, we will need to work with this canvas so we can program our browser game. In this post you'll learn how to add the canvas tags to your webpage and save the canvas in a JavaScript variable.

Adding the Canvas Tag to Your Webpage

In case you are not too familiar with HTML, I first summarize what it means to write HTML and add the canvas tag: The very first thing we need to do is open a simple text editor (not a word processor) like Notepad. I prefer working with Notepad ++ but any text editor will work. Then we need to define the document as HTML by adding the <! DOCTYPE HTML> </ HTML> tags. Now you should save this document as game.HTML for example. What you call the file is up to you. However, what matters is the HTML extension. Without this it will not work. Next we need to define what the body, in other words the content, of our webpage will be. We do this by adding the body tags. Finally, inside these body tags we can write the important canvas tag: <canvas> </ canvas>.

Identifying the Canvas

So that we can work with the canvas and start animating our game inside of it, we need a simple way to identify it. The best way to do this is by giving it an id. To keep things simple and clear we give it an id of "canvas". So all you need to write now is <canvas id = "canvas"> </ canvas>. Keep in mind that we are certainly preparing the canvas for our game. The canvas itself is only a platform that we can use to run our game inside.

Saving the Canvas in JavaScript

Programming HTML5 browser games means writing a lot of JavaScript. As a matter of fact, we could not even create a game with HTML only. But how does JavaScript have access to the canvas tag? JavaScript is actually made to go through an HTML document and search for elements so the programmer can then modify them. We will do the exact same thing with our canvas. Luckily, we've given our canvas an id which makes it much easier for us to access it in JavaScript. So what we will do now in JavaScript is tell the code to look for an element with the id of canvas and save it in a JavaScript variable. Again, to keep things simple we will save it in a variable called canvas.

Source

Leave a Reply