Drawing a Rectangle

Learn how to draw an SVG rectangle.

We'll cover the following

SVG rectangle

In this lesson, we will explore another important graphical element, the rectangle. The rectangle is one of the graphical elements of SVG and is represented by the <rect> tag.

Let’s go into detail about rect by drawing it in the given example.

Code for drawing rectangle

Explanation

See the following explanation to better understand how the above code works.

  • From line 1 to line 5 in the JavaScript tab, an SVG has been created in the body tag using the append function. Then we have defined height, width, boundary color, and boundary width using the attr method.

  • From line 7 to line 12 in the JavaScript tab, we have created a rectangle using the rect, then we have defined position x and y relative to the origin using the attr method, color #00A5E3 (Irish Blue) using the attr method, and width and height of the rect using the attr method.

Following is an illustration that will help you understand different attributes of rect and its position relative to the origin.

Roundhead rectangle

We can draw another variant of a rectangle known as the roundhead rectangle by using an rx attribute of the rect graphical element. The rx attribute is known as the curve radius of the rect element.

Let’s draw the roundhead rectangle by using the same code as in the drawing of the rectangle but we will only change the rx attr of the rect to make the rectangle round head.

Code for Roundhead rectangle

Note: The value of rx should not be greater than 50% of the width. Otherwise, it will look like an ellipse rather than a roundhead rectangle.