HTML canvas rect() method
Example
Draw a 150*100 pixels rectangle:
JavaScript:
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.rect(20,20,150,100);
ctx.stroke();
Try it »
Browser support





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:
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 »
Canvas object