The Scalable Vector Graphics (SVG) format is a vector image format for creating two-dimensional graphics, with support for interactivity and animation. SVG files are XML-based text files that can be manually edited and (at least in principle) searched. SVG produces a DOM tree (not a “flat,” canvas-like image).
SVG images can be standalone documents (which is rare), or included in a web page. Contemporary browsers can handle <svg>...</svg>
elements included in HTML documents. SVG files can also be included like
other images: <img src="file.svg" />
. In this case, it is mandatory that
the SVG file declares the appropriate namespaces:
<svg
xmlns=
"http://www.w3.org/2000/svg"
xmlns:svg=
"http://www.w3.org/2000/svg"
>
A W3C SVG Working Group was formed in 1998, a first standard (SVG 1.0) was released in 2001. Work is in progress for an all-new version (SVG 2) that will integrate SVG with HTML5. A draft standard for SVG 2 became a W3C Candidate Recommendation in 2016.
SVG defines a number of renderable graphics elements, such as basic shapes, text elements, and lines and curves. The appearance of such elements can be controlled through presentational attributes, which control size, position, color, and so on.
SVG further defines several structural elements that are used to organize the information within an SVG document. Using structural elements, it is possible to group other elements together into complex units, which can then be reused or transformed together.
SVG makes it possible to apply transformations to translate, rotate,
or stretch elements. A transformation is specified for an individual
element or for a group of elements through the transform
attribute.
In general, SVG elements are rendered in document order, with the consequence that earlier elements appear to be visually “behind” later elements in the document. Elements that occur later in the document will occlude elements that are mentioned earlier.
SVG uses graphical coordinates, with the origin in the top left corner and the vertical axis running downward. Positions and sizes are measured in dimensionless user coordinates. The absolute size of the graph (and the elements it contains) is determined by the rendering device.
Finally, SVG documents can receive user events and invoke appropriate event handlers. Documents can change in response to events, thus providing a form of interactive graphical user interface (GUI).
SVG provides explicit tags for a set of predefined simple shapes.
Each shape has a set of specific attributes that control size and
position. All shapes accept the usual presentational attributes to
modify the shape’s appearance. (See Table B-1. Not included
are <polyline>
and <polygon>
, because typically the <path
>
element is used for such shapes; see the next section.)
Tag | Specific attributes | Description |
---|---|---|
|
|
Coordinates of upper-left corner |
|
Width and height |
|
|
Horizontal and vertical corner radius |
|
|
|
Center Coordinates |
|
Radius |
|
|
|
Center coordinates |
|
The horizontal and vertical radius |
|
|
|
Starting point coordinates |
|
End point coordinates |
The <path>
element is the most low-level drawing command in SVG. It can
draw arbitrary shapes using a command language implementing a form of
turtle graphics. The <path>
element has only a single specific
attribute (in addition to the usual representational attributes, of course):
d
The value of the d
attribute consists of a string of whitespace-separated
commands and coordinates. (See Table B-2.)
A command is specified through a single letter. All commands come in two forms: as an uppercase letter or a lowercase letter. An uppercase letter indicates that the following set of coordinates are absolute
coordinates, whereas a lowercase letter indicates that the following set of coordinates is to be interpreted as relative coordinates. Coordinates in the <path>
element are always unitless. Negative coordinates are legal.
It is customary to let path specifications begin with an M
command to place the pen at a well-defined position.
Commands exist to draw straight lines, Bézier curves, and ellipsoidal arcs. In particular the latter ones require a large number of parameters; see the SVG reference for complete details. In practice, command strings are commonly generated automatically, although it is also possible to write them explicitly. Two examples:
Command letter | Coordinates | Description |
---|---|---|
|
|
Move to (invisible—no line drawn). |
|
|
Line to |
|
|
Vertical line |
|
|
Horizontal line |
|
Line to the first point; forming a proper (line) miter join with it. (This command can occur in the middle of the command string, not just at the end.) |
|
|
|
Quadratic Bézier curve, from the current position to |
|
multiple points |
Quadratic Bézier curve through multiple control points. |
|
|
Cubic Bézier curve, from the current position to |
|
multiple points |
Cubic Bézier curve through multiple control points. |
|
|
Ellipsoidal arc from the current position (the starting point of the arc)
to |
Text can be included in an SVG image using the <text>
element.
The <text>
element may include <tspan>
elements, which allow
the styling or positioning of pieces of text relative to the
surrounding text. The <textPath>
element can be used to render
text along a path defined by a <path>
element.
With the exception of text-anchor
, which is only applicable to
<text>
elements, the attributes in Table B-3 apply to both
<text>
and <tspan>
elements.
Attribute | Description |
---|---|
|
Absolute position |
|
Position relative to default text position (not relative to the parent element) |
|
Rotation angle for each glyph, clockwise in degrees |
|
Controls the alignment of the text relative to its origin.
Legal values are |
Text elements behave exactly like other graphical elements when it comes
to color: the color of each glyph’s body is controlled through the
fill
attribute, and the stroke
attribute controls the color of an outline
around the glyph. Specifying a separate stroke color only makes sense
for sufficiently large font size; for most ordinary font sizes
you will want to use stroke="none"
.
The <text>
element does not include a mechanism for line breaks:
multiline text must be constructed from individual <text>
elements.
Further mechanisms exist to control the rendering of each glyph in a text individually and to select fonts and font properties. Check the SVG reference for details.
SVG defines a large number of presentational attributes; Table B-4 lists the most commonly used ones. Additional attributes exist to control the treatment of line ends and line joins (miter joins).
The most frequently used presentational attributes are probably
stroke
and fill
, which control the color that is used to draw
the the outline and interior of shapes and other elements.
Because the default values are not attractive, it is
generally necessary to set these two attributes explicitly. Two
issues frequently cause confusion:
SVG does not have a color
attribute, instead you must use fill
and stroke
.
The default value for fill
is black
; the default value for
stroke
is none
. (This means that setting fill="none"
on an
element without also updating its stroke
attribute makes it invisible!)
Attribute | Description |
---|---|
|
The color of an element’s outline. Defaults to |
|
The width of an element’s outline. Defaults to |
|
The opacity of an element’s outline, as a floating point number between 0
(fully transparent) and 1 (fully opaque). Defaults to |
|
Controls the pattern of dashes and gaps used to draw an element’s outline. |
|
The color of an element’s interior. Defaults to |
|
The opacity of an element’s interior, as a floating point number between 0
(fully transparent) and 1 (fully opaque). Defaults to |
|
The font family to render a text element, such as:
|
|
The font size for rendering a text element. The size can be given in
user coordinates (without explicit units), in points, as a percentage,
in pixels, or |
|
The font style to render a text element. Legal values are
|
|
The font weight to render a text element. Legal values are
|
|
The shape of the cursor that is displayed when the mouse pointer is over
an element. Legal values include |
|
The opacity of an element or a group of elements (when applied to the
SVG |
|
Controls the rendering of an element. When set to |
|
Controls the visibility of an element. When set to |
a The |
Colors are specified using CSS3 color syntax. The standard allows for a great variety of color formats; Table B-5 shows some of them. (See MDN CSS <color> for more detail and the complete list of named colors.)
Attribute | Description |
---|---|
|
One of the 148 predefined colornames, such as |
|
An RGB value as hexadecimal string, where each color channel
is given as a hexadecimal number between |
|
As before, but including transparency information: |
|
An RGB value using function call notation. The arguments must either all
be integers between 0 and 255 (inclusive) or all be percentages between
|
|
As before, but including transparency information. The opacity parameter
|
|
An HSL (hue, saturation, lightness) value. The |
|
As before, but including transparency information. The opacity parameter
|
a A zero in the alpha channel always expresses a fully transparent color. |
In addition, the keyword none
is a legal value for stroke
and fill
.
It signifies that no color will be applied.
SVG elements can be translated, rotated, stretched, and sheared using
the transform
attribute on an element.
In conjunction with the <g>
element, transformations allow moving complex groups of elements to their final position (without having to
update the positional attributes in each element).
Transformations enable visual effects that are not directly supported by the existing graphical elements (such as an ellipse with tilted axes or diagonally oriented text).
Transforms are applied to elements using the transform
attribute.
Table B-6 lists the possible values for this attribute. The
transform
attribute can contain a sequence of transformations, which
will be applied right-to-left (mathematical notation)! Some examples:
<ellipse
cx=
"0"
cy=
"0"
rx=
"10"
ry=
"20"
transform=
"rotate(30)"
/>
<text
x=
"0"
y=
"0"
transform=
"translate(100,100) rotate(15)"
>
Hello</text>
Operation | Description |
---|---|
|
Translates the current element by |
|
Rotates the current element in counterclockwise direction by the angle
|
|
Scales the current element in horizontal and vertical direction by
the supplied scale factors. The scale factors should be floating-point
numbers. If |
|
Apply shear transformations along the horizontal or vertical axis. |
|
Apply a general affine transformation (see notes). |
Reflections can be expressed as scale transformations with negative
factors: scale(-1,1)
is a reflection about the vertical axis,
scale(1,-1)
is a reflection about the horizontal one, and scale(-1,-1)
is a point reflection through the origin.
The general affine transformation in two dimensions can be expressed in matrix notation as follows:
All transformations in Table B-6 can be expressed in terms of this transformation:
translate(u,v) = matrix(1, 0, 0, 1, u, v) scale(g,h) = matrix(g, 0, 0, h, 0, 0) rotate(q) = matrix(cos(q), sin(q), -sin(q), cos(q), 0, 0 ) rotate(q,u,v) = translate(u,v) rotate(q) translate(-u,-v) skewX(q) = matrix(1, 0, tan(q), 1, 0, 0) skewY(q) = matrix(1, tan(q), 0, 1, 0, 0)
The origin for SVG transformations (important for rotations and
scale operations) is the origin of the SVG itself; by default it is located
in the upper-left corner. However, when the transform
attribute is used
on the outermost <svg>
element, it is interpreted as a CSS (not SVG)
transform, and therefore takes the center of the element as origin. For
more information about the importance of the origin and for practical advice
when using SVG transformations, see “SVG Transformations”.
SVG defines a number of structural elements. These elements are not rendered themselves, but only serve to organize other elements within the document. (See Table B-7.)
Of particular importance is the <g>
(group) element. The <g>
is a
container element that acts as a common parent for its children.
It combines its children into a composite element
that can henceforth be treated as a unit. (The function of the <g>
element is therefore comparable to the “group/ungroup” functionality
familiar from many drawing programs.) Presentational attributes set on
the <g>
element are inherited by its children. Transformations applied
to the <g>
element are applied to all of its children. This makes it
possible to move a set of graphical elements to a different position
as a unit (without having to update the position of each element
individually). When rotated, the content of the <g>
element is
rotated rigidly about a common center.
Element | Description |
---|---|
|
The |
|
Groups elements into a composite element that can be transformed or reused
as a unit. Any presentation attribute defined on |
|
A |
|
The |
The following snippet shows how several of the elements in Table B-7 might be used together in an SVG document:
<defs>
<g
id=
"doublecircle"
>
<circle
cx=
"0"
cy=
"0"
r=
"3"
fill=
"red"
/>
<circle
cx=
"0"
cy=
"0"
r=
"5"
fill=
"none"
stroke=
"red"
/>
</g>
</defs>
<use
x=
"10"
y=
"20"
href=
"#doublecircle"
/>
By default, the origin of an SVG graph lies in the upper-left corner, with the horizontal axis running left to right, and the vertical
axis pointing down. Lengths in SVG are usually specified as pure
numbers without units; a single unit is treated as equivalent to one
pixel. The other length units familiar from CSS (em
, ex
, px
, pt
, cm
, mm
, and in
) are available, but rarely used. Current CSS and SVG
standards fix the pixel density at 96 dpi, thus defining the physical length
of one pixel.
An SVG graph is, in principle, infinitely large. The width
and
height
attributes set on the <svg>
tag do not define the size
of the figure, but only the size of the viewport. The viewport is
an area of the given size in which part or all of the SVG figure
will be shown: essentially, a “window” onto the overall SVG.
By default, the viewport will show the part of the SVG image directly
underneath it, with the origin of the figure in the top-left corner
of the viewport and with the same units of length used for the viewport
and the figure. To select a specific part of the entire SVG image
to be shown in the viewport, the viewBox
attribute on the <svg>
element
must be set explicitly. Using the viewBox
attribute, a rectangular area of
the entire figure can be specified, which will then be scaled to fit into
the viewport. (This is also the proper way to rescale SVG figures.) The details
of this mapping (from the area specified by the viewBox
to the visible
area of the viewport) are controlled by the preserveAspectRatio
attribute,
which controls not only the aspect ratio, but also the alignment of the
selected area within the viewport.
SVG elements can be styled using CSS mechanisms and syntax. All presentational attributes (see Table B-4) can be set through styles.
CSS style directives can be included in an SVG document, using
<style>...</style>
tags inside the <defs>
section:
<svg>
<defs>
<style>
circle { fill: blue } .strong { fill: red }</style>
</defs>
<circle
cx=
"100"
cy=
"100"
r=
"5"
/>
<rect
class=
"strong"
x=
"200"
y=
"200"
width=
"50"
height=
"20"
/>
</svg>
It is also possible to link an external stylesheet, for example, by including
a line like this in the <head>...</head>
section of the HTML page:
<link
href=
"styles.css"
rel=
"stylesheet"
>
Finally, inline style directives are legal, but less commonly used:
`<circle
style=
"fill: green"
/>
`
The tutorial on the Mozilla Development Network (MDN) contains more detail, but moves relatively quickly and can be recommended as a place to start: MDN SVG Tutorial. On the MDN, you can also find a reference for elements, MDN SVG Element Reference, and attributes, MDN SVG Attribute Reference.
The SVG 2 Draft Standard itself is quite readable and, of course, the definitive source of information.