HTML5 Canvas

Canvas <canvas> is an html5 element using to display a square rectangle object on a  web page and allow other components added inside the canvas.

We can use javascript to insert an images, write, draw text and sprites on the <canvas>. With the built-in object known as getContext(“2d”) including properties and methods to draw, we can use <canvas> to create any games run in web browsers.

Ready to make game, remember this html page structure

<html>
<head>
<title>Start to make game with canvas and javascript</title>
</head>
<body>
<!--the web content -->
</body>
</html>

To create a canvas we just use its tag <canvas> and put it inside the body.

Step 1: Create a <canvas id=”gameblock”/> inside the <body></body> tags and set the id for it as gameblock

Step 2: Create a javascript declare a new variable name as gameRoom with the method startGame()

<script>

        var gameRoom = {

            canvas: document.getElementById("gameblock"),

            startGame: function () {

                this.canvas.width = 300;

                this.canvas.height = 300;

                this.context = this.canvas.getContext("2d");

            }

        };

        gameRoom.startGame(); // call this to set the width, height of the canvas

</script>

Step 3: Understand the properties canvas.width, canvas.height to set the width and height for the canvas gameblock. Also, we assign the canvas gameblock to the property canvas of gameRoom

Step 4: Run the game by viewing the createcanvas.html on any web browsers to check

Step 5: You will see nothing but the white page because the canvas, we haven’t set the color background for it. Try to use <style>#gameblock{background-color:whitesmoke;}</style> and refresh the createcanvas.html page

 

Now, you know how to create a canvas and set up the properties of it. In the next tutorial, we will learn how to add the sprite object components to the canvas.