HTML5 Game - Canvas Rectangle Methods

Introduction

The following code shows how to draw a rectangle.

Demo

ResultView the demo in separate window

<html>
    <head>
        <script>
            window.onload = function(){
                let canvas = document.getElementById("myCanvas");
                let context = canvas.getContext("2d");
                //from  w w w. j  a va 2  s .  c o  m
                context.rect(canvas.width / 2 - 100, canvas.height / 2 - 50, 200, 100);
                context.fillStyle = "#8ED6FF";
                context.fill();
                context.lineWidth = 5;
                context.strokeStyle = "black";
                context.stroke();
            };
        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
        </canvas>
    </body>
</html>

Note

We can draw a simple rectangle by using the rect() method:

context.rect(x,y,width,height); 

The rect() method draws a rectangle at the position x, y, and defines its size with width and height.

The code above uses fillStyle and fill().

We can assign a fill color using the fillStyle method and fill the shape using fill().

It is a good practice to use fill() before using stroke().

In addition to the rect() method, there are two more methods to draw a rectangle:

  • fillRect()
  • strokeRect()

fillRect() method

You can draw the rectangle and fill it in a single method via fillRect():

context.fillRect(x,y,width,height); 

The fillRect() method is equivalent to using the rect() method followed by fill().

You need to define the fill style prior to calling it.

strokeRect() method

We can draw a rectangle and stroke it with a single method using the strokeRect() method:

context.strokeRect(x,y,width,height); 

The strokeRect() method combines the rect() method and stroke() method.

You need to define the stroke style prior to calling this method.

Related Topics