Latest web development tutorials
 

HTML canvas rect() Method

< Canvas Object

Example

Draw a 150*100 pixels rectangle:

YourbrowserdoesnotsupporttheHTML5canvastag.

JavaScript:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.rect(20,20,150,100);
ctx.stroke();
Try it Yourself »

Browser Support

The numbers in the table specify the first browser version that fully supports the method.

Method
rect() 4.0 9.0 3.6 4.0 10.1

Definition and Usage

The rect() method creates a rectangle.

Tip: Use the stroke() or the fill() method to actually draw the rectangle on the canvas.

JavaScript syntax: context.rect(x,y,width,height);

Parameter Values

Parameter 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 »

Examples

More Examples

Example

Create three rectangles with the rect() method:

Yourbrowserdoesnotsupportthecanvastag.

JavaScript:

var c=document.getElementById("myCanvas");
var ctx=c.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 »


< Canvas Object