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.
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 theappend
function. Then we have definedheight
,width
,boundary color
, andboundary width
using theattr
method. -
From line 7 to line 12 in the JavaScript tab, we have created a rectangle using the
rect
, then we have defined positionx
andy
relative to the origin using theattr
method,color
#00A5E3
(Irish Blue) using theattr
method, andwidth
andheight
of therect
using theattr
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.
Note: The value of
rx
should not be greater than50%
of thewidth
. Otherwise, it will look like an ellipse rather than a roundhead rectangle.