JavaScript: Intro to Web Game Development – Part 1: canvas element

For this series, I am going to detail how to use JavaScript to create a web based browser game by going step by step through all of the concepts involved in creating the game of Pong. I will be using parts of the tutorial written by Chris DeLeon, but greatly expanding on and customizing his code example.

The first concept to introduce when it comes to making JavaScript browser games is the use of the HTML5 canvas object. A canvas is basically a rectangular box that you can insert into any HTML document which JavaScript will use to draw on.

Here is what w3shcools.com says about the canvas element:

The HTML <canvas> element is used to draw graphics, on the fly, via JavaScript.

The <canvas> element is only a container for graphics. You must use JavaScript to actually draw the graphics.

Canvas has several methods for drawing paths, boxes, circles, text, and adding images.

Since this game will live in a web page, lets start by setting up an empty HTML document that will serve as a template.

<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>

Pong 1.0<br>

<!-- Create an HTML canvas and assign it an id. -->
<canvas id="gameCanvas" width="750" height="550" style="border:1px solid 
#000000;"></canvas>

<script>
</script>

</body>
</html>

For this project, I gave the canvas an id name of “gameCanvas” and a size 750 pixels wide by 550 pixels high. Nothing is visible on the page yet except the word “Pong 1.0”, and a 1 pixel border around the canvas, which I added just to make the canvas visible at this point. The HTML template also has <script></script> tags where the JavaScript code will live.

Here is what the canvas looks like so far:

For more information about the HTML canvas element, see:
https://www.w3schools.com/html/html5_canvas.asp