English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

HTML Reference Manual

HTML tag list

HTML canvas rect() method

rect() is a Canvas 2D API method to create a rectangle path, the starting position of the rectangle is (x, y), and the size is width and height. The4points connected by lines, the subpath is used as a closing tag, so you can fill or stroke the rectangle.

HTML canvas Reference Manual

Online Example

Draw 150*100-pixel rectangle:

Your browser does not support HTML5 canvas tag.
<!DOCTYPE html>
<html>
<head>
<title>HTML canvas rect() method usage (Basic Tutorial Website oldtoolbag.com)</title>
</head>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3>
Your browser does not support HTML5 canvas tag.
</canvas>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.rect(20,20,150,100);
ctx.stroke();
</script> 
</body>
</html>
Test and See ‹/›

Browser Compatibility

IEFirefoxOperaChromeSafari

Internet Explorer 9Firefox, Opera, Chrome, and Safari support 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 stroke() orfill() The method actually draws a rectangle on the canvas.

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

Parameter value

ParameterDescription
xX coordinate of the top-left corner of the rectangle.
yY coordinate of the top-left corner of the rectangle.
widthRectangle width, in pixels.
heightRectangle height, in pixels.

Online Example

Create three rectangles using the rect() method:

Your browser does not support the canvas tag.
<!DOCTYPE html>
<html>
<head>
<title>HTML canvas rect() method usage (Basic Tutorial Website oldtoolbag.com)</title>
</head>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3>
Your browser does not support HTML5 canvas tag.
</canvas>
<script>
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();
</script> 
</body>
</html>
Test and See ‹/›
HTML canvas Reference Manual