Canvas rect() method

Definition and usage

rect() The method creates a rectangle.

Tip:Please use stroke() or fill() The method actually draws a rectangle on the canvas.

Example

Example 1

Draw a 150*100 pixel rectangle:

Your browser does not support the HTML5 canvas tag.

JavaScript:

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

Try It Yourself

Syntax

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

Parameter value

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

Create three rectangles using the rect() method:

Your browser does not support the HTML5 canvas tag.

JavaScript:

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

Browser Support

The numbers in the table indicate the first browser version that fully supports this property.

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
4.0 9.0 3.6 4.0 10.1

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