Appendix B. An SVG Survival Kit

Introduction

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.

General Overview

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).

Shapes

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.)

Table B-1. SVG shapes
Tag Specific attributes Description

<rect>

x, y

Coordinates of upper-left corner

width, height

Width and height

rx, ry

Horizontal and vertical corner radius

<circle>

cx, cy

Center Coordinates

r

Radius

<ellipse>

cx, cy

Center coordinates

rx, ry

The horizontal and vertical radius

<line>

x1, y1

Starting point coordinates

x2, y2

End point coordinates

Path

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:

dfti abin01
Table B-2. Commands for the d attribute of the <path> element
Command letter Coordinates Description

M, m

x y, dx dy

Move to (invisible—no line drawn).

L, l

x y, dx dy

Line to

V, v

y, dy

Vertical line

H, h

x, dx

Horizontal line

Z, z

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.)

Q, q

cx cy x y

Quadratic Bézier curve, from the current position to x, y, with control point at cx, cy.

T, t

multiple points

Quadratic Bézier curve through multiple control points.

C, c

cx1 cy1 cx2 cy2 x y

Cubic Bézier curve, from the current position to x, y, with control points at cx1, cy1 and cx2, cy2.

S, s

multiple points

Cubic Bézier curve through multiple control points.

A, a

rx ry phi arg sweep x y

Ellipsoidal arc from the current position (the starting point of the arc) to x, y (the end point). The parameters rx, ry, and phi determine the size of the ellipsis and its rotation relative to the coordinate system. The remaining parameters are binary flags that fix one out of the four possible solutions to this algebraic problem uniquely.

Text

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.

Table B-3. Attributes of the <text and <tspan> elements
Attribute Description

x, y

Absolute position

dx, dy

Position relative to default text position (not relative to the parent element)

rotate

Rotation angle for each glyph, clockwise in degrees

text-anchor

Controls the alignment of the text relative to its origin. Legal values are start, middle, and end. (For scripts that are inherently left-to-right, this is equivalent to left alignment, centered, and right alignment, respectively.)

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.

Presentational Attributes

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!)

Table B-4. Common presentational attributes
Attribute Description

stroke

The color of an element’s outline. Defaults to none.

stroke-width

The width of an element’s outline. Defaults to 1.

stroke-opacity

The opacity of an element’s outline, as a floating point number between 0 (fully transparent) and 1 (fully opaque). Defaults to 1.

stroke-dasharray

Controls the pattern of dashes and gaps used to draw an element’s outline.

fill

The color of an element’s interior. Defaults to black.

fill-opacity

The opacity of an element’s interior, as a floating point number between 0 (fully transparent) and 1 (fully opaque). Defaults to 1.

font-family

The font family to render a text element, such as: Times, Times New Roman, Georgia, serif, or Verdana, Arial, Helvetica, sans-serif, or Lucida Console, Courier, monospace.a

font-size

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 "ems".a

font-style

The font style to render a text element. Legal values are normal, italic, and oblique.a

font-weight

The font weight to render a text element. Legal values are normal, bold, bolder, lighter, 100, 200, 300, 400 (the same as normal), 500, 600, 700 (the same as bold), 800, 900.a

cursor

The shape of the cursor that is displayed when the mouse pointer is over an element. Legal values include auto (the default), default, crosshair, none. Further predefined shapes exist to indicate drag-and-drop or resize actions. It is also possible to load and use an image.

opacity

The opacity of an element or a group of elements (when applied to the SVG <g> element, for instance), as a floating point number between 0 (fully transparent) and 1 (fully opaque). Defaults to 1.

display

Controls the rendering of an element. When set to none, the element and its children will be removed from the rendering tree. They will not be rendered and therefore will be invisible; they will also not be able to receive events. If applied to a <tspan> element, the element is ignored for the purposes of text layout. The display property is not inherited by children and therefore has no effect when applied to a container element.

visibility

Controls the visibility of an element. When set to visible, the element is displayed. When set to hidden or collapse, the element is invisible, but may still receive events and (if applied to a <tspan> element) will still take up room during text layout. The visibility property is inherited.

a The font- attributes are modeled after the corresponding CSS properties. Check a CSS reference for further details.

Color

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.)

Table B-5. Different ways to specify color
Attribute Description

colorname

One of the 148 predefined colornames, such as red. (The names correspond to only 140 distinct colors, because 8 colors have aliases.) Named colors do not allow transparency.

#RRGGBB

An RGB value as hexadecimal string, where each color channel is given as a hexadecimal number between 00 and FF (not case sensitive).

#RRGGBBAA

As before, but including transparency information: 00 fully transparent, FF fully opaque.a

rgb(r, g, b)

An RGB value using function call notation. The arguments must either all be integers between 0 and 255 (inclusive) or all be percentages between 0% and 100%. The percentage sign is mandatory when using percentages. Examples: rgb( 255, 0, 0 ), rgb( 100%, 0%, 0% ).

rgba(r, g, b, a)

As before, but including transparency information. The opacity parameter a can be a floating-point number between 0 and 1 or a percentage between 0% and 100%.a Examples: rgba( 255, 0, 0, 50% ), rgba( 100%, 0%, 0%, 0.5 ).

hsl(h, s, l)

An HSL (hue, saturation, lightness) value. The h argument should be an integer and is interpreted as an angle between 0 and 360 degrees (0: red, 120: green, 240: blue). Negative angles and angles greater than 360 are legal. The s and l arguments must be percentages between 0% and 100%; the percent sign is mandatory. Maximally bright colors correspond to a lightness value of 50%; 0% is black, 100% is white. Example: hsl( 0, 100%, 50% ).

hsla(h, s, l, a)

As before, but including transparency information. The opacity parameter a can be a floating-point number between 0 and 1 or a percentage between 0% and 100%.a Example: hsla( 0, 100%, 100%, 0.5 ).

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.

Transformations

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>
Table B-6. SVG transforms
Operation Description

translate(dx, dy)

Translates the current element by dx and dy.

rotate(phi, x, y)

Rotates the current element in counterclockwise direction by the angle phi, given in degrees, around the point with coordinates x and y. If the coordinates are omitted, the element is rotated around the graph’s origin.

scale(fx, fy)

Scales the current element in horizontal and vertical direction by the supplied scale factors. The scale factors should be floating-point numbers. If fy is omitted, fx is used for both directions.

skewX(phi), skewY(phi)

Apply shear transformations along the horizontal or vertical axis.

matrix(a, b, c, d, e, f)

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:

x'y'=acbdxy+ef

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”.

Structural Elements and Document Organization

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.

Table B-7. SVG structural elements
Element Description

<svg>

The <svg> element is a container that delimits an SVG document or document fragment. A document fragment delimited by <svg> elements can be directly included in an HTML5 document.

<g>

Groups elements into a composite element that can be transformed or reused as a unit. Any presentation attribute defined on <g> is inherited by its children.

<defs>

A <defs> element is a container element that can be used to collect definitions of styles or reusable components inside a document. Its use is recommended, not mandatory.

<use>

The <use> element references another element and renders a copy of this element in place of the <use> element. The referenced element may be a container element, in which case its entire content is being copied.

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" />

Coordinates, Scaling, and Rendering

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 and CSS

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" />`

Resources

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset