HTML5 Canvas - Rectangle

You can always draw a rectangle using 4 lines on the canvas. But HTML 5 provides a better way of drawing a rectangle - using the rect method. The rect method looks as follows
 context.rect(x, y, width, height); 


x,y => Coordinates of the top left corner of the rectangle
width = > width of the rectangle
height => height of the rectangle

The following code will draw a rectangle and will also fill it in yellow color.

<!DOCTYPE html5>

<canvas id ="canvas1" width="300" height="200" style="border:2px solid #FF0000;">

var c1=document.getElementById("canvas1");
var context1=c1.getContext("2d");

// Now fill the rectangle with yellow color
context1.fillStyle = 'yellow';


Try this example Online

Try this example online here. [ It opens in a new tab / windows, so you can come back ] and try to make some changes in coordinates, height and width and the fill color, to see how it looks like.

Congratulations !!! You have been able to draw a rectangle in HTML5.