Main SVG elements


In the previous lesson, we learned about SVG and how to draw a circle with it.

To create comprehensive graphs, we'll also need other shapes such as rectangles, text, and lines. Let's explore how to create these as well.

Free
4 minutes read

Rectangle

SVG rectangles are created using the <rect> element, which requires the position and size attributes. The x and y attributes specify the coordinates of the top-left corner, while width and height determine the size of the rectangle.

For example, this code will draw a blue rectangle with the top-left corner at (10,10) and dimensions of 80x50.

<rect x="10" y="10" width="80" height="50" fill="blue" />

Here is an interactive example so that you can experiment with rectangles and understand how they work.

Line

SVG lines are created using the <line> element, which requires the starting (x1, y1) and ending (x2, y2) coordinates as attributes.

For example, this code will draw a black line from the point (0,0) to the point (100,100).

<line x1="0" y1="0" x2="100" y2="100" stroke="black"/>

Here is an interactive example so that you can play a bit with lines and understand how they work.

Text

SVG text is created using the <text> element, which requires coordinates to specify where the text should be placed. The x and y attributes define the position of the starting point of the text.

For example, this code will display the text "Hello, SVG!" at the coordinates (50,50).

<text x="50" y="50" fill="black">Hello, SVG!</text>

Here is an interactive example so that you can experiment with text and understand how it works.

Circle

We talked about them already, but remember that SVG circles are created using the <circle> element, which requires the center coordinates and radius as attributes.

The cx and cy attributes specify the center point, while the r attribute determines the radius of the circle.

For example, this code will draw a red circle with a center at (50,50) and a radius of 40.

<circle cx="50" cy="50" r="40" fill="red" />

Here is an interactive example so that you can experiment with circles and understand how they work.

Exercices