Rectangles in HTML Canvas

Example

Your browser does not support the HTML5 canvas tag.

Draw a 150*100 pixel rectangle:

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.rect(20, 20, 150, 100);
ctx.stroke();

Try It Yourself

rect() method

The rect() method adds a rectangle to the path.

Syntax:

context.rect(x, y, width, height)
Parameters Description
x The x coordinate of the top-left corner of the rectangle.
y The y coordinate of the top-left corner of the rectangle.
width The width of the rectangle, in pixels.
height The height of the rectangle, in pixels.

More examples

Example

Create three rectangles using the rect() method:

Your browser does not support the canvas tag.

JavaScript:

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// Red rectangle
ctx.beginPath();
ctx.lineWidth = "6";
ctx.strokeStyle = "red";
ctx.rect(5, 5, 290, 140);
ctx.stroke();
// Green rectangle
ctx.beginPath();
ctx.lineWidth = "4";
ctx.strokeStyle = "green";
ctx.rect(30, 30, 50, 50);
ctx.stroke();
// Blue rectangle
ctx.beginPath();
ctx.lineWidth = "10";
ctx.strokeStyle = "blue";
ctx.rect(50, 50, 150, 80);
ctx.stroke();

Try It Yourself

See Also:

Complete Canvas Reference Manual of CodeW3C.com