🌱 Tim's Dev Wiki

Search IconIcon to open search


Last updated September 16, 2022.

SVG (scalable vector graphics) is an image format that defines images using vectors in XML on a cartesian plane rather than pixels, like PNG or JPEG, which we call bitmapped or raster image formats.

Some advantages SVGs have over other image formats:

You can define any image using vectors or pixels, however which choice is better depends on how you expect to use the image.

# Drawing SVGs

It’s hard to create SVGs by manually writing the XML code for the individual vectors that comprise an image. Instead, you should be using tools like Figma, Illustrator, Photoshop, etc. and you can also use some of these tools to convert between SVG and raster image formats. You can even use javascript libraries like D3.js to create SVGs.

# SVG Elements

Just as HTML provides elements like <p>, <div>, <table> for describing documents, SVG provides elements like <g>, <circle>, <line> for defining images.

There are lot of SVG elements. See this full reference on MDN.

# Important Details

# <svg>

<svg> is the root element of an image, just like how <html> is the root element of a document. You must always bind the xmlns to a namespace URI, eg. <svg xmlns="http://www.23.org/2000/svg">.

Using this element, we define the coordinate system: Attributes:

# <g>

<g> doesn’t draw anything, it just groups together other basic shapes. The point of doing this is to be able to apply transformations to a whole group of elements, and set attributes like fill that should be inherited by all of its children.

# <rect>

# <circle>, <ellipse>

# <line>

Lines are defined based on a starting coordinate $(x_{1}, y_1)$ and ending coordinate $(x_{2},y_2)$.


# <path>

Path elements can draw any shape, including the default ones like rect, circle, line, etc. You define them by specifying the d (data) attribute, which is a sequence of commands.

Path commands:

# <polygon>

Polygons are all n-sided shapes. You define them by simply specifying a list of points.

# <text>

You can also add text to any SVG. You control its location with x and y attributes, and just like for regular HTML text, you can apply CSS style rules like font-family, font-weight, etc.

Additional attributes specific to <text> include: