SVG: Graphics with Markup
Subscribe to my newsletter and never miss my upcoming articles
So, what is SVG?
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.
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:
- External Inclusion (using the
- 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
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>
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.
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!
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.
<svg height=”250” width=”250”> <line x1=”0” y1=”0” x2=”200” y2=”200" style="stroke: black; stroke-width: 2px;" /> </svg>
(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.
style attribute, the
stroke property defines the colour of the line (stroke), and the
stroke-width property defines the width of the line.
Please, do note that the highest values the
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
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.
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:
1. SVG Rectangles
In SVG, rectangles and squares can be created using the
<rect /> element.
<svg height="100" width="200"> <rect width="150" height="80" style="stroke: #000; stroke-width: 2px; fill: #C43271;" /> </svg>
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
height attributes of both the
<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.
<svg height="200" width="200"> <circle cx="100" cy="100" r="90" stroke="#000" stroke-width="2" fill="#C43271" /> </svg>
cx and the
cy attributes define the
y coordinates of the center of the circle (which is a point); more like:
cx means central point's
cy means central point's
y coordinate. If the
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
fill are alternatives to the
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?
<svg height="140" width="500"> <ellipse cx="200" cy="80" rx="100" ry="50" style="stroke: black; stroke-width: 2px; fill: #C43271;"/> </svg>
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:
<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:
<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:
P3. Now let's define the coordinates of each point:
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:
<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]
<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.
<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, 400) and
Example 2: A logo with SVG Polygons
6. SVG Paths
[Things are about to get scary ...]
<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.
<path d="[Path-Command][x,y] [Path-Command2][x2,y2]" />
[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 .
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.
<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>
SVG Path Commands are case insensitive. Meaning you could use lowercases instead of UPPERCASES, or vice-versa. Command
L10,87 is the same as
SVG Paths is a huge topic to discuss on its own. You can read more about it on MDN.
We can add texts to our SVG image with the
<svg> <text x="10" y="10">Hello SVG!</text> </svg>
y attributes defines where the text will appear in the viewport. The attribute
text-anchor, which can have the values
inherit, defines in which direction the text flows from the point specified. The attribute
dominant-baseline defines the vertical alignment.
<text> element's child element
<tspan>, we can group texts into several sub-groups. An example is displaying texts on different lines:
<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>
Let's take a look at Lindsay Grizzard's drawing with SVG:
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 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:
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.
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
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?
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>