Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

Canvas rect() Method

❮ Canvas Reference

Example

Draw a 150*100 pixels rectangle:

YourbrowserdoesnotsupporttheHTML5canvastag.

JavaScript:

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

ctx.beginPath();
ctx.rect(20, 20, 150, 100);
ctx.stroke();
Try it Yourself »

Description

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

See Also:

The beginPath() Method (To begin the path)

The stroke() Method (To draw the path)

The fill() Method (To fill and draw the rectangle)

The fillRect() Method (Draw a filled rectangle)


Syntax

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

Parameter Values

Param Description Play it
x The x-coordinate of the upper-left corner of the rectangle Play it »
y The y-coordinate of the upper-left corner of the rectangle Play it »
width The width of the rectangle, in pixels Play it »
height The height of the rectangle, in pixels Play it »

Return Value

NONE


More Examples

Example

Create three rectangles with the rect() method:

Yourbrowserdoesnotsupportthecanvastag.

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 »

Browser Support

The <canvas> element is an HTML5 standard (2014).

rect() is supported in all modern browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes 9-11

❮ Canvas Reference