rect method

The rect method draws a rectangle at the given point. This rectangle will become visible only if you apply the stroke or fill method. In the first case there will be a stroke, and in the second - a shape.

Syntax

javascriptcontext.rect(x, y, width, height)

Example

Let's draw a path with rect:

html<canvas id="canvas" width="200" height="200" style="background: #f4f4f4;"></canvas>
javascriptlet canvas = document.querySelector('#canvas');
let ctx = canvas.getContext('2d');

ctx.rect(50, 50, 100, 75);
ctx.stroke();

Результат:

Example

Now let's draw a shape:

html<canvas id="canvas" width="200" height="200" style="background: #f4f4f4;"></canvas>
javascriptlet canvas = document.querySelector('#canvas');
let ctx = canvas.getContext('2d');

ctx.rect(50, 50, 100, 75);
ctx.fill();

Результат:

See also

  • the fillRect method
    that draws a filled rectangle
  • the strokeRect method
    that draws the stroke of a rectangle