THE WORLD'S LARGEST WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

HTML canvas rect() Method

HTML canvas Reference HTML Canvas Reference

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

Internet Explorer Firefox Opera Google Chrome Safari

Internet Explorer 9, Firefox, Opera, Chrome, and Safari support the rect() method.

Note: Internet Explorer 8 and earlier versions, do not support the <canvas> element.


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 »


HTML canvas Reference HTML Canvas Reference