Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

HTML canvas rect() method

HTML canvas rect() method

HTML canvas Reference HTML canvas Reference Manual

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 »


Browser support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

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

**Note:** Internet Explorer 8 and earlier versions do not support .


Definition and Usage

The rect() method creates a rectangle.

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

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

Parameter value

Parameters Description
x The x-coordinate of the upper-left corner of the rectangle.
y The y-coordinate of the upper-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 via 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 »


HTML canvas Reference HTML canvas Reference Manual