The rect() method of the HTML canvas is used to create a rectangle. The <canvas> element allows you to draw graphics on a web page using JavaScript. Every canvas has two elements that describes the height and width of the canvas i.e. height and width respectively.
Following is the syntax −
context.fillRect(p,q,width,height);
Above,
- p: The x-coordinate of the upper-left corner of the rectangle
- q: The y-coordinate of the upper-left corner of the rectangle
- width: Width of the rectangle
- height: Height of the rectangle
Let us now see an example to implement the rect() method of canvas −
Example
<!DOCTYPE html> <html> <body> <canvas id="myCanvas" width="450" height="350" style="border:2px solid blue;"> Your browser does not support the HTML5 canvas tag.</canvas> <script> var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); ctx.beginPath(); ctx.rect(100, 60, 200, 200); ctx.fillStyle = "orange"; ctx.fill(); ctx.beginPath(); ctx.rect(110, 90, 180, 120); ctx.fillStyle = "yellow"; ctx.fill(); </script> </body> </html>