HTML5 Game - Canvas Drawing Rectangles

Introduction

Let us draw rectangles.

The following table describes the relevant methods, all of which we apply to the context object, not the canvas itself.

Name DescriptionReturns
clearRect(x, y, w, h)Clears the specified rectangle void
fillRect(x, y, w, h) Draws a filled rectangle void
strokeRect(x, y, w, h) Draws an unfilled rectanglevoid

All three of these methods take four arguments.

The first two, x and y are the offset from the top-left corner of the canvas element.

The w and h arguments specify the width and height of the rectangle to draw.

The following code shows the use of the fillRect and strokeRect methods.

Demo

ResultView the demo in separate window

<!DOCTYPE HTML>
<html>
    <head>
        <title>Example</title>
        <style>
            canvas {border: thin solid black; margin: 4px}
        </style>
    </head>
    <body>
        <canvas id="canvas" width="500" height="140">
            Your browser doesn't support the <code>canvas</code> element
        </canvas>
        <script>
            let ctx = document.getElementById("canvas").getContext("2d");
            /*from  w w w. j  av a2s  . c om*/
            let offset = 10;
            let size = 50;
            let count = 5;
            
            for (let i = 0; i < count; i++) {
                ctx.fillRect(i * (offset + size) + offset, offset, size, size);
                ctx.strokeRect(i * (offset + size) + offset, (2 * offset) + size, 
                    size, size);
            }
        </script>
    </body>
</html>

Related Topic