Drawing rectangles using canvas in JavaScript

Squares and rectangles don't have to be drawn using the combinations moveTo, lineTo - there are simpler methods for this. Let's take a look at them.

strokeRect method

The strokeRect(x, y, width, height) method draws a rectangle path at the given point. The first two parameters set the coordinates of the point where the upper left corner of the drawn rectangle will be.

Let's draw a rectangle with strokeRect (assuming ctx is already there):

<canvas width="200" height="200" style="background: #f4f4f4;"></canvas> let canvas = document.querySelector('canvas'); let ctx = canvas.getContext('2d'); ctx.strokeRect(50, 50, 100, 75);

:

fillRect method

The fillRect(x, y, width, height) method works the same way as strokeRect, except it draws a filled rectangle. Let's look at an example:

<canvas width="200" height="200" style="background: #f4f4f4;"></canvas> let canvas = document.querySelector('canvas'); let ctx = canvas.getContext('2d'); ctx.fillRect(50, 50, 100, 75);

:

rect method

The following method rect(x, y, width, height) also draws a rectangle. But this rectangle will become visible only if you apply the stroke or fill method. In the first case there will be an outline, and in the second - a shape.

Let's draw an outline with rect:

<canvas width="200" height="200" style="background: #f4f4f4;"></canvas> let canvas = document.querySelector('canvas'); let ctx = canvas.getContext('2d'); ctx.rect(50, 50, 100, 75); ctx.stroke();

:

Now let's draw a shape:

<canvas width="200" height="200" style="background: #f4f4f4;"></canvas> let canvas = document.querySelector('canvas'); let ctx = canvas.getContext('2d'); ctx.rect(50, 50, 100, 75); ctx.fill();

:

clearRect method

The following clearRect(x, y, width, height) method works like an eraser, clearing the rectangular area and making the content completely transparent.

Let's draw a square with fillRect and erase its part with clearRect:

<canvas width="200" height="200" style="background: #f4f4f4;"></canvas> let canvas = document.querySelector('canvas'); let ctx = canvas.getContext('2d'); ctx.fillRect(50, 50, 100, 100); ctx.clearRect(75, 75, 50, 50);

:

enru