BUY THIS BOOK
This print book is out of stock, with no immediate plans to reprint.

Safari Books Online

What is this?


Looking to Reprint this content?


SVG Essentials
SVG Essentials By J. David Eisenberg
February 2002
Pages: 364

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Getting Started
SVG, which stands for Scalable Vector Graphics, is an application of XML that makes it possible to represent graphic information in a compact, portable form. Interest in SVG is growing rapidly, and tools to create and view SVG files are already available from major companies. This chapter begins with a description of the two major systems of computer graphics, and describes where SVG fits into the graphics world. The chapter concludes with a brief example that uses many of the concepts that we will explore in detail in the following chapters.
The two major systems for representing graphic information on computers are raster and vector graphics.
In raster graphics, an image is represented as a rectangular array of picture elements or pixels (see Figure 1-1). Each pixel is represented either by its RGB color values or as an index into a list of colors. This series of pixels, also called a bitmap, is often stored in a compressed format. Since most modern display devices are also raster devices, displaying an image requires a viewer program to do little more than uncompress the bitmap and transfer it to the screen.
Figure 1-1: Raster graphic rectangle
In a vector graphic system, an image is described as a series of geometric shapes (see Figure 1-2). Rather than receiving a finished set of pixels, a vector viewing program receives commands to draw shapes at specified sets of coordinates.
Figure 1-2: Vector graphic rectangle
If you think of producing an image on graph paper, raster graphics work by describing which squares should be filled in with which colors. Vector graphics work by describing the grid points at which lines or curves are to be drawn. Some people describe vector graphics as a set of instructions for a drawing, while bitmap graphics (rasters) are points of color in specific places. Vector graphics "understand" what they are — a square "knows" it's a square and text "knows" that it's text. Because they are objects rather than a series of pixels, vector objects can change their shape and color, whereas bitmap graphics cannot. Also, all text is searchable because it really is text, no matter how it looks or how it is rotated or transformed.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Graphics Systems
The two major systems for representing graphic information on computers are raster and vector graphics.
In raster graphics, an image is represented as a rectangular array of picture elements or pixels (see Figure 1-1). Each pixel is represented either by its RGB color values or as an index into a list of colors. This series of pixels, also called a bitmap, is often stored in a compressed format. Since most modern display devices are also raster devices, displaying an image requires a viewer program to do little more than uncompress the bitmap and transfer it to the screen.
Figure 1-1: Raster graphic rectangle
In a vector graphic system, an image is described as a series of geometric shapes (see Figure 1-2). Rather than receiving a finished set of pixels, a vector viewing program receives commands to draw shapes at specified sets of coordinates.
Figure 1-2: Vector graphic rectangle
If you think of producing an image on graph paper, raster graphics work by describing which squares should be filled in with which colors. Vector graphics work by describing the grid points at which lines or curves are to be drawn. Some people describe vector graphics as a set of instructions for a drawing, while bitmap graphics (rasters) are points of color in specific places. Vector graphics "understand" what they are — a square "knows" it's a square and text "knows" that it's text. Because they are objects rather than a series of pixels, vector objects can change their shape and color, whereas bitmap graphics cannot. Also, all text is searchable because it really is text, no matter how it looks or how it is rotated or transformed.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Scalability
Although they are not as popular as raster graphics, vector graphics have one feature that makes them invaluable in many applications — they can be scaled without loss of image quality. As an example, here are two drawings of a cat. Figure 1-3 was made with raster graphics; Figure 1-4 is a vector image. Both are shown as they appear on a screen that displays 72 pixels per inch.
Figure 1-3: Raster image of cat
Figure 1-4: Vector image of cat
When a display program zooms in on the raster graphic, it must find some way to expand each pixel. The simplest approach to zooming in by a factor of four is to make each pixel four times as large. The results, shown in Figure 1-5, are not particularly pleasing.
Figure 1-5: Expanded raster image
Although it is possible to use techniques such as edge-detection and anti-aliasing to make the expanded image more pleasing, these techniques are time-consuming. Furthermore, since all the pixels in a raster graphic are equally anonymous, there's no guarantee that an algorithm can correctly detect edges of shapes. Anti-aliasing results in something like Figure 1-6.
Figure 1-6: Expanded anti-aliased raster image
Expanding a vector image by a factor of four, on the other hand, merely requires the display program to multiply all the coordinates of the shapes by four and redraw them at the full resolution of the display device. Thus, Figure 1-7, which is also a screenshot from a 72 dot per inch screen, shows crisp, clear edges on the lines with significantly less of the stair-step effects of the expanded raster image.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
SVG's Role
In 1998, the World Wide Web Consortium formed a working group to develop a representation of vector graphics as an XML application. Because SVG is an XML application, the information about an image is stored as plain text, and it brings the advantages of XML's openness, transportability, and interoperability.
CAD and graphic design programs often store drawings in a proprietary binary format. By adding the ability to import and export drawings in SVG format, applications gain a common, standard format for interchanging information.
Since it is an XML application, SVG cooperates with other XML applications. A mathematics textbook, for example, could use XSL Formatting Objects for explanatory text, MathML to describe equations, and SVG to generate the graphs for the equations.
The SVG working group's specification is an official World Wide Web Consortium Recommendation. Some applications such as Adobe Illustrator and Jasc WebDraw export drawings in SVG format. On the Web, SVG viewer plug-ins let users view presentations with many of the same scripting and animation capabilities that Flash has. Since the SVG files are XML, text in the SVG display is available to any user agent that can parse XML.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating an SVG Graphic
In this section, we will write an SVG file that produces the image of the cat that we showed earlier in the chapter. This example introduces many of the concepts that we will explain in further detail in subsequent chapters. This file will be a good example of how to write an example file, which is not necessarily the way you should write an SVG file that will be part of a finished project.
We start Example 1-1 with the standard XML processing instruction and DOCTYPE declaration. The root <svg> element defines the width and height of the finished graphic in pixels. The <title> element's content is available to a viewing program for use in a title bar or as a tooltip pointer, and the <desc> element lets you give a full description of the image.
Example 1-1. Basic structure of an SVG document
<?xml version="1.0"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"
    "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">

<svg width="140" height="170">
<title>Cat</title>
<desc>Stick Figure of a Cat</desc>
<!— the drawing will go here —>
</svg>
We draw the cat's face by adding a <circle> element. The element's attributes specify the center x-coordinate, center y-coordinate, and radius. The (0,0) point is the upper left corner of the picture. x coordinates increase as you move horizontally to the right; y coordinates increase as you move vertically downwards.
The circle's location and size are part of the drawing's structure. The color in which it is drawn is part of its presentation. As is customary with XML applications, we want to separate structure and presentation for maximum flexibility. Presentation information is contained in the style attribute. Its value will be a series of presentation properties and values, as described in Appendix B, in Section B.1. We'll use a stroke color of black for the outline, and a fill color of none to make the face transparent. The SVG is shown in Example 1-2, and its result in Figure 1-8.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Coordinates
The world of SVG is an infinite canvas. In this chapter, we'll discuss how you tell a viewer program which part of this canvas you're interested in, what its dimensions are, and how you locate points within that area.
The area of the canvas that your document intends to use is called the viewport. You establish the size of this viewport with the width and height attributes on the <svg> element. The values of these attributes can be simply a number, which is presumed to be in pixels; this is said to be specified in user coordinates. You may also specify width and height as a number followed by a unit identifier, which can be one of the following:
em
The font size of the default font, usually equivalent to the height of a character
ex
The height of the letter x
px
Pixels
pt
Points (1/72 of an inch)
pc
Picas (1/6 of an inch)
cm
Centimeters
mm
Millimeters
in
Inches
Examples:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Viewport
The area of the canvas that your document intends to use is called the viewport. You establish the size of this viewport with the width and height attributes on the <svg> element. The values of these attributes can be simply a number, which is presumed to be in pixels; this is said to be specified in user coordinates. You may also specify width and height as a number followed by a unit identifier, which can be one of the following:
em
The font size of the default font, usually equivalent to the height of a character
ex
The height of the letter x
px
Pixels
pt
Points (1/72 of an inch)
pc
Picas (1/6 of an inch)
cm
Centimeters
mm
Millimeters
in
Inches
Examples:
<svg width="200" height="150">
<svg width="200px" height="200px">
Both of these specify an area 200 pixels wide and 150 pixels tall.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using Default User Coordinates
When you do not use unit specifiers on your <svg> element, the viewer sets up a coordinate system where the horizontal, or x-coordinate, increases as you go to the right, and the vertical, or y-coordinate, increases as you move vertically downward. The upper left corner of the viewport is defined to have an x- and y-coordinate of zero. This point, written as (0, 0) is also called the origin. The coordinate system is a pure geometric system; points have neither width nor height, and the grid lines are considered infinitely thin. We'll return to this subject in Chapter 3.
Example 2-1 establishes a viewport two hundred pixels wide and two hundred pixels high, then draws a rectangle whose upper left corner is at coordinate (10, 10) with a width of 50 pixels and a height of 30 pixels. Figure 2-1 shows the result, with rulers and a grid to show the coordinate system.
Example 2-1. Using default coordinates
<svg width="200" height="200">
    <rect x="10" y="10" width="50" height="30"
        style="stroke: black; fill: none;"/>
</svg>
Figure 2-1: Rectangle using default coordinates
Even if you don't specify units in the viewport, you may still use them in some SVG shape elements, as we do in Example 2-2. Figure 2-2 shows the result, with rulers and a grid to show the coordinate system.
Example 2-2. Explicit use of units
<svg width="200" height="200">
    <rect x="10mm" y="10mm" width="15mm" height="10mm"
        style="stroke:black; fill:none;"/>
</svg>
Specifying units in the <svg> element does not affect coordinates given without units in other elements. Example 2-3 shows a viewport set up in millimeters, but the rectangle is still drawn at pixel (user) coordinates, as you see in Figure 2-3.
Example 2-3. Units on the svg element
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Specifying User Coordinates for a Viewport
In the examples so far, numbers without units have been considered to be pixels. Sometimes this is not what you want. For example, you might want to set up a system where each user coordinate represents one-sixteenth of a centimeter. (We're using this coordinate system to prove a point, not to show a paragon of good design.) In this system, a square that is 40 units by 40 units will display as 2.5 centimeters on a side.
To accomplish this effect, you set the viewBox attribute on the <svg> element. The value of this attribute consists of four numbers that represent the minimum x-coordinate, minimum y-coordinate, width, and height of the user coordinate system that you want to superimpose on the viewport.
So, to set up the sixteen-units-per-centimeter coordinate system for a four centimeter by five centimeter drawing, you'd use this starting tag:
<svg width="4cm" height="5cm" viewBox="0 0 64 80">
Example 2-4 lists the SVG for a picture of a house, displayed using the new coordinate system.
Example 2-4. Using a viewBox
<svg width="4cm" height="5cm" viewBox="0 0 64 80">
   <rect x="10" y="35" width="40" height="40"
      style="stroke: black; fill: none;"/>
   <!-- roof -->
   <polyline points="10 35, 30 7.68, 50 35" 
      style="stroke:black; fill: none;"/>
   <!-- door -->
   <polyline points="30 75, 30 55, 40 55, 40 75"
      style="stroke:black; fill: none;"/>
   </svg>
Figure 2-4 shows the result. The grid and darker numbers show the new user coordinate system; the lighter numbers are positioned at one-centimeter intervals.
Figure 2-4: New user coordinates
The numbers you specify for the value of the viewBox attribute may be separated by commas or whitespace. If either the width or height is zero, none of your graphic will display. It is an error to specify a negative value for the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Preserving Aspect Ratio
In the previous example, the aspect ratio, or ratio of width to height, of the viewport and the viewBox were identical (4/5 = 64/80). What happens, though, if the aspect ratio of the viewport and the viewBox are not the same, as in this example, where viewBox has an aspect ratio of one to one, but the viewport has an aspect ratio of one to three?
<svg width="45px" height="135px" viewBox="0 0 90 90">
There are three things that SVG can do in this situation:
  • Scale the graphic uniformly according to the smaller dimension so the graphic will fit entirely into the viewport. In the example, the picture would become half its original width and height. We'll show you examples of this in Section 2.4.2.
  • Scale the graphic uniformly according to the larger dimension and cut off the parts that lie outside the viewport. In the example, the picture would become one and a half times its original width and height. We'll show you examples in Section 2.4.3.
  • Stretch and squash the drawing so that it fits precisely into the new viewport. (That is, don't preserve the aspect ratio at all.) We will cover this in Section 2.4.4.
In the first case, since the image will be smaller than the viewport in one dimension, you must specify where to position it. In the example, the picture will be scaled uniformly to a width and height of 45 pixels. The width of the reduced graphic fits the width of the viewport perfectly, but you must now decide whether the image meets (is aligned with) the top, middle, or bottom of the 135-pixel viewport height.
In the second case, since the image will be larger than the viewport in one dimension, you must specify which area is to be sliced away. In the example, the picture will be scaled uniformly to a width and height of 135 pixels. Now the height of the graphic fits the viewport perfectly, but you must decide whether to slice off the right side, left side, or both edges of the picture to fit within the 45-pixel viewport width.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Nested Systems of Coordinates
You can establish a new viewport and system of coordinates at any time by putting another <svg> element into your document. The effect is to create a "mini-canvas" upon which you can draw. We used this technique to create illustrations such as Figure 2-5. Rather than drawing the rectangles, then rescaling and positioning the cat inside each one (the brute force approach), we took these steps:
  • Draw the blue rectangles on the main canvas
  • For each rectangle, define a new <svg> element with the appropriate preserveAspectRatio attribute
  • Draw the cat into that new canvas (with <use>), and let SVG do the heavy lifting
Here's a simplified example that shows a circle on the main canvas, then inside a new canvas that's outlined by a blue rectangle that's also on the main canvas. Figure 2-8 is the result we wish to achieve.
Figure 2-8: Nested viewport example
First, generate the SVG for the main coordinate system and the circle. Note that we've established the user coordinates to coincide exactly with the viewport in this document.
<svg width="200px" height="200px" viewBox="0 0 200 200">
    <circle cx="25" cy="25" r="25" style="stroke: black; fill: none;"/>
</svg>
The result is in Figure 2-9.
Figure 2-9: Circle in main viewport
Now, draw the boundary of the box showing where we want the new viewport to be:
<svg width="200px" height="200px" viewBox="0 0 200 200">
    <circle cx="25" cy="25" r="25" style="stroke: black; fill: none;"/>
    <rect x="100" y="5" width="30" height="80"
       style="stroke: blue; fill: none;"/>
</svg>
This produces Figure 2-10.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Basic Shapes
Once a coordinate system is established in the <svg> tag, you are ready to begin drawing. In this chapter, we will show the basic shapes you can use to create the major elements of most drawings: lines, rectangles, polygons, circles, and ellipses.
SVG lets you draw a straight line with the <line> element. Just specify the x- and y-coordinates of the line's endpoints. Coordinates may be specified without units, in which case they are considered to be user coordinates, or with units such as em, in, etc. as described in Chapter 2, in Section 2.1. The SVG in Example 3-1 draws several lines; the reference grid in Figure 3-1 is not part of the SVG that you see here.
<line x1="start-x" y1="start-y"
 x2="end-x" y2="end-y">
Example 3-1. Basic lines
<svg width="200px" height="200px" viewBox="0 0 200 200">
   <!-- horizontal line -->
   <line x1="40" y1="20" x2="80" y2="20" style="stroke: black;"/>
   <!-- vertical line -->
   <line x1="0.7cm" y1="1cm" x2="0.7cm" y2="2.0cm" style="stroke: black;"/>
   <!-- diagonal line -->
   <line x1="30" y1="30" x2="85" y2="85" style="stroke: black;"/>
</svg>
Figure 3-1: Basic lines
Lines are considered to be strokes of a pen that draws on the canvas. The size, color, and style of the pen stroke are part of the line's presentation. Thus, these characteristics will go into the style attribute.
As mentioned in Chapter 2, the canvas grid lines are infinitely thin. Where, then, does a line or stroke fall in relation to the grid line? The answer is that the grid line falls in the center of a stroke. Example 3-2 draws some lines where the stroke width has been set to ten user coordinates to make the effect obvious. The result, in Figure 3-2, has the grid lines drawn in so you can see the effect clearly.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Lines
SVG lets you draw a straight line with the <line> element. Just specify the x- and y-coordinates of the line's endpoints. Coordinates may be specified without units, in which case they are considered to be user coordinates, or with units such as em, in, etc. as described in Chapter 2, in Section 2.1. The SVG in Example 3-1 draws several lines; the reference grid in Figure 3-1 is not part of the SVG that you see here.
<line x1="start-x" y1="start-y"
 x2="end-x" y2="end-y">
Example 3-1. Basic lines
<svg width="200px" height="200px" viewBox="0 0 200 200">
   <!-- horizontal line -->
   <line x1="40" y1="20" x2="80" y2="20" style="stroke: black;"/>
   <!-- vertical line -->
   <line x1="0.7cm" y1="1cm" x2="0.7cm" y2="2.0cm" style="stroke: black;"/>
   <!-- diagonal line -->
   <line x1="30" y1="30" x2="85" y2="85" style="stroke: black;"/>
</svg>
Figure 3-1: Basic lines
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Stroke Characteristics
Lines are considered to be strokes of a pen that draws on the canvas. The size, color, and style of the pen stroke are part of the line's presentation. Thus, these characteristics will go into the style attribute.
As mentioned in Chapter 2, the canvas grid lines are infinitely thin. Where, then, does a line or stroke fall in relation to the grid line? The answer is that the grid line falls in the center of a stroke. Example 3-2 draws some lines where the stroke width has been set to ten user coordinates to make the effect obvious. The result, in Figure 3-2, has the grid lines drawn in so you can see the effect clearly.
Example 3-2. Demonstration of stroke-width
<svg width="200px" height="200px" viewBox="0 0 200 200">
   <!-- horizontal line -->
   <line x1="30" y1="10" x2="80" y2="10"
      style="stroke-width: 10; stroke: black;"/>
   <!-- vertical line -->
   <line x1="10" y1="30" x2="10" y2="80"
      style="stroke-width: 10; stroke: black;"/>
   <!-- diagonal line -->
   <line x1="25" y1="25" x2="75" y2="75"
      style="stroke-width: 10; stroke: black;"/>
</svg>
Figure 3-2: Demonstration of stroke-width
You can specify the stroke color in a variety of ways:
  • One of the color keyword names: aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, purple, red, silver, teal, white, and yellow.
  • A six-digit hexadecimal specifier in the form # rr gg bb, where rr is the red component, gg is the green component, and bb is the blue component in the range 0-ff.
  • A three-digit hexadecimal specifier in the form
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Rectangles
The rectangle is the simplest of the basic shapes. You specify the x- and y-coordinates of the upper left corner of the rectangle, its width, and its height. The interior of the rectangle is filled with the fill color you specify. If you do not specify a fill color, the interior of the shape is filled with black. The fill color may be specified in any of the ways described in Section 3.2.2, or it may take the value none to leave the interior unfilled and thus transparent. You may also specify a fill-opacity in the same format as you did in Section 3.2.3. Both fill and fill-opacity are presentation properties, and belong in the style attribute.
After the interior is filled (if necessary), the outline of the rectangle is drawn with strokes, whose characteristics you may specify as you did for lines. If you do not specify a stroke, the value none is presumed, and no outline is drawn. Example 3-6 draws several variations of the <rect> element. Figure 3-6 shows the result, with a grid for reference.
Example 3-6. Demonstration of the rectangle element
<svg width="200px" height="200px" viewBox="0 0 200 200">
   <!-- black interior, no outline -->
   <rect x="10" y="10" width="30" height="50"/>

   <!-- no interior, black outline -->
   <rect x="50" y="10" width="20" height="40"
      style="fill: none; stroke: black;"/>

   <!-- blue interior, thick semi-transparent red outline -->
   <rect x="10" y="70" width="25" height="30"
      style="fill: #0000ff;
         stroke: red; stroke-width: 7; stroke-opacity: 0.5;"/>

   <!-- semi-transparent yellow interior, dashed green outline -->
   <rect x="50" y="70" width="35" height="20"
       style="fill: yellow; fill-opacity: 0.5;
          stroke: green; stroke-width: 2; stroke-dasharray: 5 2"/>
</svg>
Figure 3-6: Demonstration of the rect element
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Circles and Ellipses
To draw a circle, use the <circle> element and specify the center x-coordinate, center y-coordinate, and radius with the cx, cy, and r attributes. As with a rectangle, the default is to fill the circle with black and draw no outline unless you specify some other combination of fill and stroke.
An ellipse also needs an x-radius and a y-radius in addition to a center x- and y-coordinate. The attributes for these radii are named rx and ry.
In both circles and ellipses, if the cx or cy is omitted, it is presumed to be zero. If the radius is zero, no shape will be displayed; it is an error to provide a negative radius. Example 3-8 draws some circles and ellipses which are shown in Figure 3-9.
Example 3-8. Demonstration of circles and ellipses
<svg width="200px" height="200px" viewBox="0 0 200 200">
   <circle cx="30" cy="30" r="20" style="stroke: black; fill: none;"/>
   <circle cx="80" cy="30" r="20"
      style="stroke-width: 5; stroke: black; fill: none;"/>

   <ellipse cx="30" cy="80" rx="10" ry="20" 
      style="stroke: black; fill: none;"/>
   <ellipse cx="80" cy="80" rx="20" ry="10" 
      style="stroke: black; fill: none;"/>
</svg>
Figure 3-9: Demonstration of circle and ellipse elements
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The polygon Element
In addition to rectangles, circles, and ellipses, you may want to draw hexagons, octagons, stars, or arbitrary closed shapes. The <polygon> element lets you specify a series of points that describe a geometric area to be filled and outlined as described earlier. The points attribute consists of a series of x- and y-coordinate pairs separated by commas or whitespace. You must give an even number of entries in the series of numbers. You don't have to return to the starting point; the shape will automatically be closed. Example 3-9 uses the <polygon> element to draw a parallelogram, a star, and an irregular shape.
Example 3-9. Demonstration of the polygon element
<svg width="200px" height="200px" viewBox="0 0 200 200">
    <!-- parallelogram -->
    <polygon points="15,10  55, 10  45, 20  5, 20"
        style="fill: red; stroke: black;"/>

    <!-- star -->
    <polygon
        points="35,37.5  37.9,46.1 46.9,46.1  39.7,51.5
            42.3,60.1  35,55  27.7,60.1  30.3,51.5
            23.1,46.1  32.1,46.1"
        style="fill: #ccffcc; stroke: green;"/>

    <!-- weird shape -->
    <polygon 
        points="60 60,  65 72,  80 60,  90 90, 72 80, 72 85, 50 95"
        style="fill: yellow; fill-opacity: 0.5; stroke: black;
            stroke-width: 2;"/> 
</svg>
The results, with a grid in the background for reference, are displayed in Figure 3-10.
Figure 3-10: Demonstration of the polygon element
For the polygons shown so far, it's been easy to fill the shape. Since none of the lines forming the polygon cross over one another, the interior is easily distinguished from the exterior of the shape. However, when lines cross over one another, the determination of what is inside the polygon is not as easy. The SVG in Example 3-10 draws such a polygon. In Figure 3-11, is the middle section of the star considered to be inside or outside?
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The polyline Element
Finally, to round out our discussion of basic shapes, we'll return to straight lines. Sometimes you want a series of lines that does not make a closed shape. You can use multiple <line> elements, but if there are many lines it might be easier to use the <polyline> element. It has the same attributes as <polygon>, except that the shape is not closed. Example 3-12 draws the symbol for an electrical resistor, shown in Figure 3-13.
Example 3-12. Example of the polyline element
<svg width="200px" height="200px" viewBox="0 0 200 200">

<polyline
    points="5 20, 20 20, 25 10, 35 30, 45 10,
        55 30, 65 10, 75 30, 80 20, 95 20"
    style="stroke: black; stroke-width: 3; fill: none;"/> 

</svg>
Figure 3-13: Example of the polyline element
It's best to set the fill property to none when using <polyline>; otherwise, the SVG viewer attempts to fill the shape, sometimes with startling results like those in Figure 3-14.
Figure 3-14: Example of filled polyline
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Line Caps and Joins
When drawing a <line> or <polyline>, you may specify the shape of the endpoints of the lines by setting the stroke-linecap style property to one of the values butt, round, or square. Example 3-13 shows these three values, with gray guide lines showing the actual endpoints of the lines. You can see in Figure 3-15 that round and square extend beyond the end coordinates; butt, the default, ends exactly at the specified endpoint.
Example 3-13. Values of the stroke-linecap property
<line x1="10" y1="15" x2="50" y2="15"
    style="stroke-linecap: butt; stroke-width: 15;"/>

<line x1="10" y1="45" x2="50" y2="45"
    style="stroke-linecap: round; stroke-width: 15;"/> 

<line x1="10" y1="75" x2="50" y2="75"
    style="stroke-linecap: square; stroke-width: 15;"/> 

<!-- guide lines -->
<line x1="10" y1="0" x2="10" y2="100" style="stroke: #999;"/>
<line x1="50" y1="0" x2="50" y2="100" style="stroke: #999;"/>
Figure 3-15: Values of the stroke-linecap attribute
You may specify the way lines connect at the corners of a shape with the stroke-linejoin style property, which may have the values miter (pointed), round (round -- what did you expect?), or bevel (flat). Example 3-14 produces the result shown in Figure 3-16.
Example 3-14. Values of the stroke-linejoin attribute
<polyline
    style="stroke-linejoin: miter; stroke: black; stroke-width: 12;
    fill: none;"
    points="30 30, 45 15, 60 30"/> 

<polyline
    style="stroke-linejoin: round; stroke: black; stroke-width: 12;
    fill: none;"
    points="90 30, 105 15, 120 30"/> 

<polyline
    style="stroke-linejoin: bevel; stroke-width: 12; stroke: black;
    fill: none;"
    points="150 30, 165 15, 180 30"/> 
Figure 3-16:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Basic Shapes Reference Summary
The following tables summarize the basic shapes and presentation styles in SVG.
Table 3-1 summarizes the basic shapes available in SVG.
Table 3-1: Table of shape elements
ShapeDescription
<line x1="start-x" y1="start-y" x2="end-x" y2="end-y"/>
Draws a line from the starting point at coordinates (start-x, start-y) to the ending point at coordinates (end-x, end-y).
<rect x="left-x" y="top-y" width="width" height="height"/>
Draws a rectangle whose upper left corner is at (left-x, top-y) with the given width and height.
<circle cx="center-x" cy="center-y" r="radius"/>
Draws a circle with the given radius, centered at (center-x, center-y).
<ellipse cx="center-x" cy="center-y" rx="x-radius" ry="y-radius"/>
Draws an ellipse with the given x-radius and y-radius centered at (center-x, center-y).
<polygon points="points-specifications"/>
Draws an arbitrary closed polygon whose outline is described by the points-specification. The points are specified as pairs of x- and y-coordinates. These are user coordinates only; you may not add a length unit specifier.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Document Structure
We've casually mentioned that SVG lets you separate a document's structure from its presentation. In this chapter, we're going to compare and contrast the two, discuss the presentational aspects of a document in more detail, and then show some of the SVG elements that you can use to make your document's structure clearer, more readable, and easier to maintain.
As we mentioned in Chapter 1, in Section 1.4.2, one of XML's goals is provide a way to structure data and separate this structure from its visual presentation. Consider the drawing of the cat from that chapter; you recognize it as a cat because of its structure — the position and size of the geometric shapes that make up the drawing. If we were to make structural changes, such as shortening the whiskers, rounding the nose, and making the ears longer and rounding their ends, the drawing would become one of a rabbit, no matter what the surface presentation might be. The structure, therefore, tells you what a graphic is.
This is not to say that information about visual style isn't important; had we drawn the cat with thick purple lines and a gray interior, it would have been recognizable as a cat, but its appearance would have been far less pleasing. These differences are shown in Figure 4-1, albeit without the color differences. XML encourages you to separate structure and presentation; unfortunately, many discussions of XML emphasize structure at the expense of presentation. We'll right this wrong by going into detail about how you specify presentation in SVG.
Figure 4-1: Structure versus presentation
SVG lets you specify presentational aspects of a graphic in four ways; with inline styles, internal stylesheets, external stylesheets, and presentation attributes. Let's examine each of these in turn.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Structure and Presentation
As we mentioned in Chapter 1, in Section 1.4.2, one of XML's goals is provide a way to structure data and separate this structure from its visual presentation. Consider the drawing of the cat from that chapter; you recognize it as a cat because of its structure — the position and size of the geometric shapes that make up the drawing. If we were to make structural changes, such as shortening the whiskers, rounding the nose, and making the ears longer and rounding their ends, the drawing would become one of a rabbit, no matter what the surface presentation might be. The structure, therefore, tells you what a graphic is.
This is not to say that information about visual style isn't important; had we drawn the cat with thick purple lines and a gray interior, it would have been recognizable as a cat, but its appearance would have been far less pleasing. These differences are shown in Figure 4-1, albeit without the color differences. XML encourages you to separate structure and presentation; unfortunately, many discussions of XML emphasize structure at the expense of presentation. We'll right this wrong by going into detail about how you specify presentation in SVG.
Figure 4-1: Structure versus presentation
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using Styles with SVG
SVG lets you specify presentational aspects of a graphic in four ways; with inline styles, internal stylesheets, external stylesheets, and presentation attributes. Let's examine each of these in turn.
Example 4-1 uses inline styles. This is exactly the way we've been using presentation information so far; we set the value of the <style> attribute to a series of visual properties and their values as described in Appendix B, in Section B.1.
Example 4-1. Use of inline styles
<circle cx="20" cy="20" r="10"
    style="stroke: black; stroke-width: 1.5; fill: blue; fill-opacity: 0.6"/>
You don't need to place your styles inside each SVG element; you can create an internal stylesheet to collect commonly-used styles that you can apply to all occurrences of a particular element, or use as named classes to apply to individual elements. Example 4-2 sets up an internal stylesheet that will draw all circles in a blue double-thick dashed line with a light yellow interior. We have placed the stylesheet within a <defs> element, which we will discuss later in this chapter.
The example then draws several circles. The circles in the second row of Figure 4-2 have inline styles that override the specification in the internal stylesheet.
Example 4-2. Use of internal stylesheet
<svg width="200px" height="200px" viewBox="0 0 200 200">
<defs>
<style type="text/css"><![CDATA[
    circle {
        fill: #ffc;
        stroke: blue;
        stroke-width: 2;
        stroke-dasharray: 5 3
    }     
    ]]></style>
</defs>

<circle cx="20" cy="20" r="10"/>
<circle cx="60" cy="20" r="15"/>
<circle cx="20" cy="60" r="10" style="fill: #cfc"/>
<circle cx="60" cy="60" r="15" style="stroke-width: 1; 
    stroke-dasharray: none;"/>
</svg>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Document Structure -- Grouping and Referencing Objects
While it is certainly possible to define any drawing as an undifferentiated list of shapes and lines, most non-abstract art consists of groups of shapes and lines that form recognizable named objects. SVG has elements that let you do this sort of grouping to make your documents more structured and understandable.
The <g> element gathers all of its child elements as a group, and often has an id attribute to give that group a unique name. Furthermore, each group may have its own <title> and <desc> to identify it for text-based XML applications or to aid in accessibility for visually-impaired users. In addition to the conceptual clarity that comes from the ability to group and document objects, the <g> element also provides notational convenience. Any styles you specify in the starting <g> tag will apply to all the child elements in the group. In Example 4-5, this saves us from having to duplicate the style="fill:none; stroke:black;" on every element shown in Figure 4-4. It is also possible to nest groups within one another, although we won't show any examples of this until Chapter 5.
You may think of the <g> element as analogous to the Group Objects function in programs such as Adobe Illustrator. It also serves a similar function to the concept of layers in such programs; a layer is also a grouping of related objects.
Example 4-5. Simple use of the g element
<svg width="240px" height="240px" viewBox="0 0 240 240">
<title>Grouped Drawing</title>
<desc>Stick-figure drawings of a house and people</desc>

<g id="house" style="fill: none; stroke: black;">
    <desc>House with door</desc>
    <rect x="6" y="50" width="60" height="60"/>
    <polyline points="6 50, 36 9, 66 50"/>
    <polyline points="36 110, 36 80, 50 80, 50 110"/>
</g>

<g id="man" style="fill: none; stroke: black;">
    <desc>Male human</desc>
    <circle cx="85" cy="56" r="10"/>
    <line x1="85" y1="66" x2="85" y2="80"/>
    <polyline points="76 104, 85 80, 94 104" />
    <polyline points="76 70, 85 76, 94 70" />
</g>

<g id="woman" style="fill: none; stroke: black;">
    <desc>Female human</desc>
    <circle cx="110" cy="56" r="10"/>
    <polyline points="110 66, 110 80, 100 90, 120 90,