Spicy Yoghurt | Last updated: 2 Februari 2019 | HTML5 game

Draw a rectangle on the canvas

In this HTML5 game development tutorial you will learn how to get a reference to the <canvas> element in your JavaScript code and perform your first drawing operation.


This tutorial requires the basic HTML5 file you have created in the previous tutorial. If you skipped that step, you can download the basic HTML5 file with canvas here.

Get a reference to the canvas

Now, let's continue. To perform drawing operations later on, you'll need a decent reference in your code to your canvas. Expand the <script> tags with the following JavaScript code:

                    
                        <script>
                            "use strict";

                            // Declare as variable
                            var canvas;
                            var context;
                            
                            // Listen to the onLoad event
                            window.onload = init;

                            // Trigger init function when the page has loaded
                            function init(){
                                canvas = document.getElementById('canvas');
                                context = canvas.getContext('2d');

                                // Draw something!
                                draw();
                            }

                            function draw(){
                                // Get a random color, red or blue
                                context.fillStyle = Math.random() > 0.5? '#ff8080' : '#0099b0';

                                // Draw a rectangle on the canvas
                                context.fillRect(25, 25, 100, 75);
                            }
                        </script>
                    
                    
The window.onload event will trigger once the whole page is loaded. This will make sure all elements and resources on the page are available. The init() function is set as the event handler. Once the onload event fires, init() will be called.

Inside the init() function, the canvas is stored for later reference by calling getElementById(). Once the references are made, the first drawing operation is performed.

This is what you get:

Draw on the canvas

When you add the previous code to your index.html file, and run the file in the browser, you will actually see something getting draw on the canvas. It's a big rectangle!

By calling draw() in the init() function, a rectangle has been draw to the canvas. You can modify the params inside the function to create rectangles of different sizes and colors.

Draw with a random color

With the current code, the rectangle is either red or blue. This is because every time the page is loaded a new random color is picked in the draw() function, by using Math.random() to pick a color. You can try to refresh this page a couple of times and see the color getting changed.

The random color is used to demonstrate the fact that you are not looking at a static image. You are drawing your own graphics!

Final code

You can draw on the canvas now. The total code looks like this:

                    
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">

    <title>Game development tutorial - Spicy Yoghurt</title>
    <meta name="description" content="HTML5 game development tutorial">
    <meta name="author" content="Spicy Yoghurt">
</head>
<body>
    <canvas id="canvas" style="border:1px solid lightgrey;">
        Your browser does not support the HTML5 canvas tag.
    </canvas>
    <script>
        "use strict";

        // Declare as variable
        var canvas;
        var context;

        // Listen to the onLoad event
        window.onload = init;

        // Trigger init function when the page has loaded
        function init() {
            canvas = document.getElementById('canvas');
            context = canvas.getContext('2d');

            // Draw something!
            draw();
        }

        function draw() {
            // Get a random color, red or blue
            context.fillStyle = Math.random() > 0.5 ? '#ff8080' : '#0099b0';

            // Draw a rectangle on the canvas
            context.fillRect(25, 25, 100, 75);
        }
    </script>
</body>
</html>

                    
                    
You can copy and store this code in a file, or download the complete file here. Feel free to ask questions in the comments.

In the next step of the tutorial, you will learn how to do multiple drawing operations. You will create a game loop!

Leave a comment