HTML canvas rect()Method

Canvas 对象参考手册Canvas object

Example

Draw a 150*100 pixel 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 ExplorerFirefoxOperaGoogle ChromeSafari

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:Please use thestroke()orfill()method to actually draw the rectangle on the canvas.

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

Parameter Values

Parameter 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 with the rect() method:

Your browser does not support the canvas tag.

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 对象参考手册Canvas object

Other Extensions