HTML5 Game - Canvas Shape Rectangle

Drawing Rectangles via path

The rect method adds a rectangular sub-path to the current path.

It is useful to add a rectangle to a more complex shape.

Demo

ResultView the demo in separate window

<!DOCTYPE HTML>
<html>
    <head>
        <title>Example</title>
        <style>
            canvas {border: thin solid black}
            body > * {float:left;}
        </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   www  .j a  va  2 s .c om
            ctx.fillStyle = "yellow";
            ctx.strokeStyle = "black";
            ctx.lineWidth = 4;
       
            ctx.beginPath();
            ctx.moveTo(110, 10);
            
            ctx.lineTo(110, 100);
            ctx.lineTo(10, 10);
            ctx.closePath();
            
            ctx.rect(110, 10, 100, 90);
            ctx.rect(110, 100, 130, 30);
            
            ctx.fill();
            ctx.stroke();           
        </script>
    </body>
</html>

We don't need to use the moveTo method when using the rect method because we specify the coordinates of the rectangle as the first two method arguments.