How to Build HTML5 Games: Drawing Rectangles with Canvas

In this tutorial, we will walk through the basics of creating an HTML5 game using the canvas element. Specifically, we will learn how to draw rectangles on the canvas using JavaScript.

Step 1: Setting Up the HTML

We start by creating a simple HTML page that includes a canvas element where the game will be displayed.

Live Demo

Your browser does not support HTML5 canvas. Please shift to a new browser
Canvas Code
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8">
        <script type="text/javascript">
            function pageLoaded() {
                // Get canvas and context
                var canvas = document.getElementById("testCanvas");
                var context = canvas.getContext("2d");
                
                // Filled rectangles with different colors
                context.fillStyle = "#FF0000";  // Red
                context.fillRect(200, 10, 100, 100);
                
                context.fillStyle = "#00FF00";  // Green
                context.fillRect(50, 70, 90, 30);
                
                // Stroked rectangles with different colors
                context.strokeStyle = "#0000FF";  // Blue
                context.lineWidth = 2;
                context.strokeRect(110, 10, 50, 50);
                
                context.strokeStyle = "#FF00FF";  // Purple
                context.strokeRect(30, 10, 50, 50);
                
                // Cleared rectangles (will show white)
                context.clearRect(210, 20, 30, 20);
                context.clearRect(260, 20, 30, 20);
            }
        </script>
    </head>
    <body onload="pageLoaded();">
        <canvas width="640" height="480" id="testCanvas" style="border: 1px solid black;">
            Your browser does not support HTML5 canvas. Please shift to a new browser
        </canvas>
    </body>
</html>

Conclusion

In this blog, we learned how to set up an HTML5 canvas and draw rectangles using JavaScript. Stay tuned for more tutorials on building HTML5 games!