How to Draw Basic Shapes with SVG
SVG (Scalable Vector Graphics) has a similar syntax as HTML. They are both based on XML. Since HTML5 we can simply inline the code of an SVG image inside an HTML file like below.
This opens up a lot of cool options. We can access parts of an image with JavaScript to make something interactive or generate art with code. We can also move the styling to CSS and animate image elements with CSS.
We define an svg
element with its width
and height
properties. This defines the drawing canvas where the coordinates go from the 0,0
coordinate from the top-left corner and grow downwards and to the right.
We can place shapes onto this canvas by coordinates. In the next chapter, we learn how to adjust this coordinate system with the viewBox property.
The SVG element often has an xmlns
property as well. If the image
is inlined in HTML this can be omitted.
How to draw a Circle in SVG
For today’s example, we draw a simple Christmas ornament. Here, we only use simple shapes: two circles and a rectangle.
To define a circle
we need to set the following properties:
- We set its center position with the
cx
andcy
properties. - We set the radius with the
r
.
We define the main part of the Christmas ornament as a circle. We set its center position on the x-axis to the middle at 100
and on the y-axis, slightly below the middle at 120
. We set a large radius and set its fill color. Hover over the element to see how it is positioned.
To add some color, we use the fill
property. This property is similar to the background-color
property in CSS for regular HTML elements.
The color value can be a color name like red
, a hex color code like #ff0000
, or a CSS function like rgb(255 0 0)
. If we don’t want to fill the shape, we can set it to none
.
How to draw a Rectangle in SVG
We draw a little cap on top of the Christmas ornament with the rect
element:
- We set the top-left position with the
x
andy
coordinate. - We set the size with the
width
andheight
properties.
We position this rectangle above the previous circle and set a smaller size. Hover over the element to see how it is positioned. We use the fill
attribute the same way as we did with the circle.
How to draw a Ring in SVG
We finish the example with the hanger on top. We use the circle
element again but with different attributes. Instead of filling it, we set the outline color with the stroke
property and the width of this stroke with stroke-width
.
We also set the fill
color to none
because the default value would be black.
The final code of the Christmas ornament is as follows:
Great! We drew our first SVG image. Now, let’s get into the next challenge!