SVG: Graphics with Markup

As front-end Web Developers, the load speed of our web pages are very crucial to us. In this era of web designing, we need images to convey messages that only words cannot explain, yet we still require our web pages to load very quickly so our visitors do not have to run away after waiting for a very long time. In this article, we’ll learn to design vector graphics with XML (Extensible Markup Language), a language quite similar to HTML; which can be written within our HTML documents and enhance our load speed. So basically, what we’re going to do is design our own images with XML tags and attributes along with all the goodies offered to us by CSS (I won’t cover using JavaScript with XML; at least, not in this article). Let’s get started!

So, what is SVG?

SVG, short for Scalable Vector Graphics, is an XML-based vector image format for two-dimensional graphics with support for interactivity and animation (Wikipedia). Behind the scenes, SVG images are just simple text files written in a markup language, describing the lines, shapes, colours and other elements such as text. Code written to create SVG images are easily readable and understandable, and such images can easily be modified with CSS, and some interactivity added to it with JavaScript. Meaning, we could have non-static images: dynamically animated graphics on our web pages; cool right?

Vector Graphics and Raster Graphics

Vector Graphics are computer graphics that are defined in terms of 2D points, which are connected by lines and curves to form polygons and other shapes. This means, with vector graphics images are similar to joining the points plotted on an SVG coordinate system (which mimics the popular Cartesian plane in Math), using the x-axis and y-axis, to form a shape or something that visually makes sense.

Raster Graphics (a.k.a bitmap images) are dot matrix data structures that represent a generally rectangular grid of pixels (points of colour), viewable via a monitor, paper, or other display medium. Raster images are stored in image files with varying formats.

SVG Support in Browsers

SVG became a W3C Recommendation in 2001 (at least, I was born by then) and is supported in the latest versions of the most popular web browsers we have now. Here is an image from Can I Use.

SVG Support in Browsers

How to Include SVG Images

So, after writing an SVG document, how do we render it on our web pages? There are two ways to achieve this:

  1. External Inclusion (using the src attribute)
  2. Internal Inclusion (writing SVG in the HTML document)

Let’s shed some light on them, shall we?

  • Importing SVG Images: We could write a stand-alone SVG document and import it just like any other image is imported with the <img /> element, along with its src attribute.

NOTE: SVG documents have the .svg extension.

  • Writing SVG in the HTML document: Preferably, we can write the SVG codes in our HTML file. So, instead of using the <img /> element we could write the code from the SVG document right at the place where we want the image to be displayed – no <img /> element needed; thanks to HTML5. In this article, we’ll be using this method.

Ayt Gyen, shun talking; let’s code already :(!

The SVG Element

In order to write an SVG image, we need an <svg> tag, just like we need an <img /> tag for including images; except this element isn’t closed the way HTML’s alter ego, XHTML, closes the <img /> element.

<svg height=”...” width=”...”>
        [ SVG Elements … ]
</svg>

The height and width attributes define the dimensions of the SVG image. The [ SVG Elements … ] is where we define our elements of design: lines, shapes, colour styles, paths, etc. If we want a rectangle, we write corresponding tags inside the <svg> element. Hence, any code written outside the SVG element will not be considered as SVG, and might be an unknown element to the browser.

SVG Coordinate System

SVG has a coordinated system which works like the Cartesian plane popularly known in Math. It also has a x-axis/y-axis coordinates even though it looks a bit different.

SVG Coordinate System

Each point is defined by a X and a Y coordinate in the user coordinate system. The units are pixels and the initial viewport coordinate system has its origin at the top-left of the viewport, with the positive x-axis pointing towards the right and the positive y-axis pointing down.

Let’s start writing some components!

SVG Lines

To create a line, the <line /> element is used. A line is simply the path that is created when two points are joined. These points use the SVG coordinate system where a point is made up of two coordinates: (x-axis, y-axis). Since we need two points to make a line, we’ll have to define two pairs of x/y coordinates: (x1, y1), for the first point; and (x2, y2), for the second point. In the SVG coordinate system, the coordinates (0, 0) is known as the origin.

Example

<svg height=”250” width=”250”>
    <line x1=”0” y1=”0” x2=”200” y2=”200" style="stroke: black; stroke-width: 2px;" />
</svg>

The (x1, y1) attributes define coordinates (0, 0) on the SVG coordinate system: this means the first point of line is located at the origin of the plane; hence, the beginning of the line. And the (x2, y2) attributes define coordinates (200, 200) on the SVG coordinate system: meaning the second point is located 200 pixels away from the origin along the x-axis and 200 pixels away from the origin along the y-axis; hence, the end of the line. The line is created tracing from the origin and moves south-east and joins the second point.

On the style attribute, the stroke property defines the colour of the line (stroke), and the stroke-width property defines the width of the line.

Tip

Please, do note that the highest values the x1 and x2 attributes can accept is the value of the width attribute on the <svg> element, since it defines the horizontal dimension; the highest values the y1 and y2 attributes can accept is the value of the height attribute on the <svg> element, since it defines the vertical dimension. Values greater than the said values will wrap around.

SVG Shapes

In order to create a very nice image, shapes are very essential elements of design. Luckily, SVG has some elements to help create various shapes. Let's name them:

  • Rectangle <rect>
  • Circle <circle>
  • Ellipse <ellipse>
  • Polyline <polyline>
  • Polygon <polygon>
  • Path <path>

1. SVG Rectangles

In SVG, rectangles and squares can be created using the <rect /> element.

Example

<svg height="100" width="200">
  <rect width="150" height="80" style="stroke: #000; stroke-width: 2px; fill: #C43271;" />
</svg>

The width and height attributes on the <rect /> element define the dimensions of the rectangle. The fill property on the style attribute defines a colour that fills the area of the shape. Since a square has equal dimensions, in order to create a square, we adjust the values of the width and height attributes of both the <svg> and <rect> elements to be equal. A demo is shown below:

2. SVG Circles

We can create circles with the SVG <circle /> element. With circles, we need a point (the center of the circle) and the radius of the circle. The radius is the distance between the center of the circle and its circumference. I'm sorry, if you don't know these things you should prolly check out your Primary 5 notebook, no offense :D.

Example

<svg height="200" width="200">
  <circle cx="100" cy="100" r="90" stroke="#000" stroke-width="2" fill="#C43271" />
</svg>

The cx and the cy attributes define the x and y coordinates of the center of the circle (which is a point); more like: cx means central point's x coordinate; cy means central point's y coordinate. If the cx and cy attributes are not defined, (0, 0) are assumed to be the coordinates for the center. The r attribute defines the radius of the circle .The attributes stroke, stroke-width and fill are alternatives to the stroke, stroke-width and fill on the style attribute (CSS).

3. SVG Ellipses

Ellipses can be created in SVG using the <ellipse /> element. It can also be used to create ovals and if its attributes are well played around with, it could be used to create a circle. But, why on earth would you use this for a circle :D?

Example

<svg height="140" width="500">
  <ellipse cx="200" cy="80" rx="100" ry="50" style="stroke: black;  stroke-width: 2px; fill: #C43271;"/>
</svg>

The rx and ry attributes define the radius along the x-axis and the y-axis, respectively.

We're not limited to just one element

So far, we've been writing only one element in the enclosing <svg></svg> element, but that's not where the world ends. We can add as many elements as required to render the image we want. In the example below, we write three ellipses - each lying on top of the other:

Example 2

<svg height="150" width="500">
  <ellipse cx="240" cy="100" rx="220" ry="30" style="fill: blue;" />
  <ellipse cx="220" cy="70" rx="190" ry="20" style="fill: cyan;" />
  <ellipse cx="210" cy="45" rx="170" ry="15" style="fill: skyblue;" />
</svg>

Cool right? :D

4. SVG Polylines

In geometry, a polyline (a.k.a. polygonal chain) is a connected series of line segments - Wikipedia. So basically,a polyline is made up of several chunks of lines connected serially. An example of a polyline is the zigzag line. I know, things are about to get nasty, but we can handle it right? :D

In SVG, polylines can be created using the <polyline /> element along with its wonderful attribute points which houses a set of pairs of coordinates of several points. Did that make sense though? Perhaps, an example would help:

Example

<svg height="200" width="500">
  <polyline points="0,0 200,0 200,200"
  style="stroke: black; stroke-width: 3px;  fill: none;" />
</svg>

When we were discussing Lines some paragraphs earlier, we said a line is formed when two points are joined; one point is the beginning of the line, and the other is the end of it. With polylines, we have more than two points, say three (based on the example above), namely: P1, P2, and P3. Now let's define the coordinates of each point:

  • P1: (0, 0)
  • P2: (200, 0)
  • P3: (200, 200)

When we chain the above points in the points attribute of the <polyline /> element separating them with a space, the point P1 is created on the origin, and then it is joined to the point P2 which is created on a location 200 pixels away from the origin along the x-axis; our first line is created. Now we join the end of the line (which ends on point P2), to the point P3 which is created on a location 200 pixels away from the origin along the x-axis and 200 pixels away from the origin along the y-axis.

Let's draw a square using polylines:

Example 2

<svg height="200" width="500">
  <polyline points="0,0 200,0 200,200 0,200 0,0"
  style="stroke: black; stroke-width: 3px;  fill: none;" />
</svg>

Trust me, you wouldn't want to use this method for squiares :D.

Example 3: Tetris Sprite with SVG Polylines

5. SVG Polygons

[Let's get ourselves more confused; just kidding :D]

The SVG <polygon /> element is used to create an image that has at least three sides. The word Polygon comes from Greek: where poly means many and gon means angle; hence, Many Angles - weird :D. Polygons are made of straight lines which all connect up to form one enclosed shape. Examples of polygons are triangles, squares, etc.

Example

<svg width="600" height="500">
  <polygon points="100,100 100,400 400,100" style="stroke: black; stroke-width: 2px; fill: #C43271;" />
</svg>

This element works similarly as the <polyline /> element, except with the <polygon /> element (on which you define the number of points you require - in our case three for a triangle) SVG automatically joins the points to form a shape. So, from the above example, we had three points: (100, 100), (100, 400) and (400, 100).

Example 2: A logo with SVG Polygons

6. SVG Paths

[Things are about to get scary ...]

The <path> element is the most powerful element in the SVG library of basic shapes. You can use it to create lines, curves, arcs and more. Paths create complex shapes by combining multiple straight lines or curved lines. - MDN

In order to use the <path /> element, we need to first know some SVG Path Commands:

  • M = move-to: shifts to a specified point without drawing a line.
  • L = line-to: constructs a line to a point.
  • H = horizontal line-to: constructs a horizontal line to a specified point.
  • V = vertical line-to: constructs a vertical line to a specified point.
  • C = curve-to: constructs a curved line to a specified point.
  • S = smooth curve-to: constructs a smooth-curved line to a specified point.
  • Q = quadratic Bézier curve: constructs a quadratic Bézier curve.
  • T = smooth quadratic Bézier curve-to: constructs a smooth quadratic Bézier curve.
  • A = elliptical Arc: constructs an arc that takes the form of an ellipse.
  • Z = close-path: closes the SVG path.

These commands are written in combination with coordinates as values of a d attribute on the <path /> element.

The Syntax

<path d="[Path-Command][x,y] [Path-Command2][x2,y2]" />

Where [Path-Command] is any of the above path commands without the brackets [] except the command Z (we'll learn why, in a second), and [x,y] stands for x/y coordinates also without the [].

The Z command does not have a pair of coordinates attached to it, and is usually (but not always) written at the end of a path node. This is because it has a default function: it draws a straight line from the current position back to the first point of the path.

Example

<svg width="400" height="250">
  <path d="M0,0 L400,0 L400,200 H0,0 V0,0" fill="none" stroke="black" stroke-width="5" />
</svg>

Tip:

SVG Path Commands are case insensitive. Meaning you could use lowercases instead of UPPERCASES, or vice-versa. Command L10,87 is the same as l10,87.

SVG Paths is a huge topic to discuss on its own. You can read more about it on MDN.

SVG Texts

We can add texts to our SVG image with the <text> element.

Example

<svg>
  <text x="10" y="10">Hello SVG!</text>
</svg>

The x and y attributes defines where the text will appear in the viewport. The attribute text-anchor, which can have the values start, middle, end or inherit, defines in which direction the text flows from the point specified. The attribute dominant-baseline defines the vertical alignment.

With the <text> element's child element <tspan>, we can group texts into several sub-groups. An example is displaying texts on different lines:

Example 2

<svg height="90" width="200">
  <text x="10" y="20" style="fill: #C43271;">Text on Several lines:
    <tspan x="10" y="45">First line,</tspan>
    <tspan x="10" y="70">Second line.</tspan>
  </text>
</svg>

Bonus Image

Let's take a look at Lindsay Grizzard's drawing with SVG:

bike.png A man cycling - by Lindsay Grizzard.

Let's take a look at the pen:

That's some creativity, but admit it; isn't the code too complex to understand? Don't worry, I already know the answer.

SVG Editors

SVG code gets more complex and sometimes our knowledge isn't enough to help us design the kind of graphics we want. There are a bunch of tools that are available for creating vector images. Some of which are online and others are offline tools. The one I recommend is Inkscape: Inkscape SVG Editor

Fortunately, there are good tutorials to get started with this amazing tool. And oh, Inkscape is free :)!

This isn't a "complete" tutorial about Scalable Vector Graphics. This article is meant to give you a head start about the topic. I'm pretty sure with what we've covered you have broadened your understanding (if you already know SVG), or now familiar with it's concepts.

Comments (8)

Enrique Bruzual's photo

Excellent article, nicely done! also keep in mind to maintain the integrity of the source file, if you’re going to edit, try to do it in the application where the file was created. Editing in multiple applications, in SVG format, may cost some unpredictable results at rendering time

Gyen Abubakar's photo

An aspiring Fullstack Developer, currently mastering front-end. I love writing and teaching others the little I know. Join me on my journey.

Well said Enrique Bruzual.

Bayu Angora's photo

I use 3 svg files (icon1.svg, icon2.svg, icon3.svg) for my footer, but the result is alaways vertically, not inline horizontal? Is the any code to make it inline horizontally?

Show all replies
Gyen Abubakar's photo

An aspiring Fullstack Developer, currently mastering front-end. I love writing and teaching others the little I know. Join me on my journey.

The answer given by Mohammad Wali works perfectly. Bayu Angora, additionally you should know to align an inline-level element, it should first be wrapped in a block-level element. Then use the text-align: center; property on the parent element:

<!-- The parent element -->
<div style="text-align: center;">

 <!-- The child element, inline-level element -->
 <span>Some dummy text ...</span>
</div>
Ruslán González's photo

Very explained article. ♥️