English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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.
Draw 150*100-pixel rectangle:
<!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 ‹/›
IEFirefoxOperaChromeSafari
Internet Explorer 9Firefox, Opera, Chrome, and Safari support rect() method.
Note:Internet Explorer 8 and earlier versions do not support the <canvas> element.
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 | Description |
---|---|
x | X coordinate of the top-left corner of the rectangle. |
y | Y coordinate of the top-left corner of the rectangle. |
width | Rectangle width, in pixels. |
height | Rectangle height, in pixels. |
Create three rectangles using the rect() method:
<!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 ‹/›