Chapter 2. SVG Document Overview

CONTENTS

In this chapter:

  •  Syntax
  •  Structure of an SVG Image (Document)
  •  The Preliminaries of an SVG Document
  •  The <svg> Element
  •  Nested SVG Elements
  •  The <g> Element
  •  Some Basic SVG Elements
  •  Painter's Model
  •  SVG Coordinate Systems
  •  Fonts

Syntax

This chapter looks at how the source code of an SVG image is structured. All SVG images, which are also SVG documents or document fragments, are also XML-compliant documents.

If you don't understand how XML syntax and, therefore, SVG syntax works, you can end up with endless frustration because an SVG viewer may not display any (or only parts) of your SVG image, if it isn't properly structured. That isn't surprising. Suppose that you are reading the instructions for the construction or configura-tion of a new gadget and you read, "Diggle the windlejump so that it is lineared upside the kindlespan." What do you do, apart from uttering some bad words or throwing the gadget out the window? You are probably stuck. If you don't structure your SVG documents properly, an SVG viewer has much the same problem: It stops. (It usually doesn't swear, though it may provide a helpful error message.) The worst message an SVG viewer has returned to me is "Junk after the document element," which I took to mean that I had made a major error (and I had).

Structure of an SVG Image (Document)

Let's begin to delve into SVG jargon and thought patterns. If you are not familiar with XML or HTML syntax and are not used to the notion of an image that is also code, it isn't always easy, but in time it all becomes second nature. Just as a concert pianist becomes free to express music with virtuoso power by becoming the master of many basic techniques, so it is with SVG.

The Preliminaries of an SVG Document

An SVG image can be completely described in an SVG document (or document fragment). The source code that describes the image is the input to an SVG rendering engine (an SVG viewer).

If you were going to draw a picture, you would want to know the kind of medium you were going to use, the tools you had available, and the size of the paper. The preliminaries of an SVG document provide much the same basic information to the SVG viewer. The XML declaration confirms what type of medium (syntax) will be used. The DOCTYPE declaration defines the allowed elements (tools, if you like). The <svg> element, called the document element, has attributes that define the size of the SVG canvas (or at least the size of the part of it on which this image will be rendered). With those three pieces of information available, an SVG viewer then has the basic information to be able to render an SVG image onscreen. Let's take a closer look at how these elements are used in practice.

All Scalable Vector Graphics documents (images) are applications of the syntax of the XML 1.0 Recommendation from the World Wide Web Consortium, or W3C. An SVG viewer should be told that the SVG document complies with XML syntax, which is done through the XML declaration. Including an XML declaration within each SVG image or document is advisable, although not compulsory. An XML declaration, at its simplest, looks like this:

<?xml version="1.0" ?> 

Although the XML declaration is optional, when you do include it, the version attribute is compulsory. Also, the XML declaration has to be on the first line of the document with no characters, not even a space, in front of it and no spaces within the <?xml part. An XML declaration can have other attributes, such as the standalone or encoding attributes, which I don't describe further just now. Your favorite vector drawing package possibly adds one or more attributes automatically, as in this declaration from Jasc WebDraw:

<?xml version="1.0" standalone="no"?> 

You don't need to add additional attributes, as long as you remember to include the version attribute. If you are working on a single platform in English, you don't need to worry too much about the other attributes. If you want to produce SVG graphics for a cross-platform, international, or multilingual audience, however, a fuller understanding of the encoding attribute, for example, is important.

The next thing in many SVG documents is typically the DOCTYPE declaration. This bit of XML terminology describes the location of the document that defines what structure the document should conform to.

NOTE

The XML syntax rules define how the elements of an XML, or SVG, document are put together, but doesn't say what those elements or their attributes should be. The DOCTYPE declaration links to a related document, called a Document Type Definition, which specifies exactly which elements are allowed and what attributes they are allowed to have. Slight differences exist between the versions of SVG.

If you view SVG documents on the Web, you may for some time, at least find a number of different DOCTYPE declarations.

If the SVG image was created to correspond to the March 2000 SVG Working Draft (the version used for the Adobe SVG Viewer version 1.0), the DOCTYPE declaration looks like this:

<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20000303  Stylable//EN"  "http://www.w3.org/TR/2000/03/WD-SVG-20000303/  DTD/svg-20000303-stylable.dtd"> 

Many early SVG images placed on the Web used this DOCTYPE declaration (the SVG filter for Corel Draw 9 still does) because it was the SVG version on which the first release of the Adobe SVG Viewer was based and many early users of SVG initially wrote their code for that version.

WARNING

If you see an image using the March 2000 type, be aware that the linking mechanism had an error, so don't just copy code to use in buttons, for example. It may not work in all current SVG viewers, although some viewers such as the Adobe SVG Viewer do, for reasons of backward compatibility, allow links to operate using incorrect syntax.

If an SVG document was written to correspond to the August 2000 Candidate Recommendation, it looks like this:

<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20000802//EN"  "http://www.w3.org/TR/2000/CR-SVG-20000802/  DTD/svg-20000802.dtd"> 

SVG images using the November 2000 Candidate Recommendation use this DOCTYPE declaration:

<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20001102//EN"  "http://www.w3.org/TR/2000/CR-SVG-20001102/  DTD/svg-20001102.dtd"> 

If you see these lines in the source code of an SVG image you are trying to understand, remember that some slight syntax changes have taken place over the intervening period and a few details will have changed. Particularly if you are using a new version of an SVG viewer, you may find that occasionally such images aren't displayed properly.

In time, the DOCTYPE declaration from the full SVG 1.0 Recommendation supplants all those shown previously.

What a DOCTYPE declaration does is to tell the SVG rendering engine (or viewer) the location of the Document Type Definition (DTD) the document that defines the structure the SVG document should have. For the July 2001 Candidate Recommendation, the details of the correct structure are defined at http://www.w3.org/TR/2001/PR-SVG-20010719/DTD/svg10.dtd. An SVG viewer may have a local copy of the DTD (which defines the correct structure) built in, but if you are using general-purpose XML tools, such as XML Writer, you may need to be online before it can check whether your SVG image's structure is valid (or correct in structure, according to the DTD).

The DOCTYPE declaration tells the SVG viewer what structure of document is being used, but you may also want to use an external style sheet to control appearance. If your SVG image is using an external Cascading Style Sheet (CSS), you might find this instruction early in an SVG image:

<?xml-stylesheet href="MyStylesheet.css"   type="text/css" ?> 

This code is an XML processing instruction. It tells the SVG viewer that it should load a file named MyStylesheet.css. Stored in the same directory as the SVG image, this text file containing CSS should use that CSS file to define the style on appropriate elements in the SVG image. A more detailed discussion of the use of CSS with SVG is in Chapter 13, "Designing SVG for Use with CSS."

You can, and often it is a good idea, to insert comments that describe the purpose of the document. SVG provides a specific element for descriptions, the <desc> element that is discussed later in this chapter, but SVG can also use ordinary XML comments that have the same syntax as HTML/XHTML comments:

<!-- This is a comment. --> 

Let's move on to look at the structure of the visible part of an SVG image.

The <svg> Element

Each SVG document or document fragment must have as its containing element the element root, a <svg> element. The <svg> element usually contains width and height attributes, which define the width and height of the SVG image. If no width or height is specified, the width and height are both assumed to be 100 percent of the available browser window.

NOTE

The area defined by the <svg> element is the SVG initial viewport. Conceptually, it is a rectangular area through which you can view what is displayed on an area of the infinite SVG canvas. The width and height attributes define its dimensions. On an outer <svg> element, the default values of the x and y attributes (which define the position of the upper-left corner of the viewport) are both zero.

If you want to create a simple SVG graphic that is 300 pixels wide by 200 pixels high, you can start with something like the following, by either hand-coding it or having a drawing tool like Jasc WebDraw create it for you:

<?xml version="1.0" standalone="no"?>  <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"        "http://www.w3.org/TR/2001/PR-SVG-20010719/         DTD/svg10.dtd">  <svg width="300" height="200"/>  <!-- Generated by Jasc WebDraw PR4(tm) on 04/03/01   10:55:39 --> 

The following syntax indicates that the <svg> element is empty:

<svg width="300" height="200"/> 

NOTE

The syntax for an empty element is a forward slash at the end of the element name (as in <svg/> , or, when attributes are present, the syntax can look like what you have read about in the text. This syntax is simply shorthand for <svg></svg> . You are likely to use empty elements quite often in your SVG images, such as when you use a rectangle, which is written as <rect/> .

If you are using WebDraw, adding any image component on the canvas tab inserts SVG elements correctly. If you are coding by hand, you need to split the <svg> element into starting (<svg>) and ending (</svg>) tags, like this:

<svg width="300" height="200">  </svg> 

The correct place to insert other SVG elements is between these starting and ending tags.

If you are hand-crafting your SVG, I suggest that you save a template that looks something like this:

<?xml version="1.0" ?>  <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"        "http://www.w3.org/TR/2001/PR-SVG-20010719/         DTD/svg10.dtd">  <svg width="" height="">  <!-- You would insert other SVG elements here,  nested within the <svg> element. -->  </svg> 

This template saves you from typing the DOCTYPE declaration and reminds you that you need to decide on a size for the display area.

So the SVG viewer now knows that what it is being presented with is intended to be a valid SVG document.

As you have just read, the width and height attributes of the <svg> element define the size of the area on which the SVG is rendered. SVG element and attribute names are case sensitive. Therefore, the name of the <svg> element must be in all lowercase letters. Also, the names of the width and height attributes also must all be in lowercase letters.

In addition to getting the correct syntax for element tags, you need to know how to write the attribute names that occur on many SVG elements. Thus, when you write the following:

<svg width="300" height="200"/> 

you have two attributes: width and height. An attribute on any SVG element takes this form:

attribute="value" 

or

attribute='value' 

Although you can use either single or double quotes, unlike in HTML, the quotes are compulsory in SVG. Because you also must use quotes in pairs, if you start with an apostrophe, for example, you must finish the attribute value with an apostrophe.

Within a <svg> element, all the other content describing the SVG image is nested:

<svg >  <!-- The other elements in the SVG document are  nested within the containing <svg> element -->  </svg> 

A <svg> element can contain a single graphics element, which in this case displays a pale bluish rectangle in the upper-left corner of the screen:

<?xml version="1.0" standalone="no"?>  <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"        "http://www.w3.org/TR/2001/PR-SVG-20010719/         DTD/svg10.dtd">  <svg width="300" height="200">  <rect x="0" y="0" width="20" height="40" style="fill:#CCCCFF;   stroke:none;"/>  </svg> 

Alternatively, a <svg> element can contain several, even dozens, of other SVG elements, some of which might themselves also contain a variety of nested SVG elements.

Nested SVG Elements

A <svg> element is like other SVG elements in that it can be nested within a <svg> element containing the SVG document. For example, to nest a <svg> element that is 100 x 100 pixels inside a <svg> element that is 400 pixels wide x 300 pixels high, you could use this code:

Listing 2.1 (NestedSVG.svg)
<?xml version="1.0" standalone="no"?>  <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"        "http://www.w3.org/TR/2001/PR-SVG-20010719/         DTD/svg10.dtd">  <svg width="500" height="400">  <svg x="100" y="100" width="300" height="200">  <rect x="1" y="1" width="298" height="198"  style="stroke:red; stroke-width:2;  fill:none;"/>  <rect x="50" y="50" width="200" height="100"  style="fill:#EEEEEE;  stroke:blue;"/>  </svg> <!-- The end tag of the nested <svg> element -->  </svg> <!-- The end tag of the outer <svg> element --> 

The first <rect> element, to be described in Chapter 3, "Creating Static Graphics Elements," simply displays a rectangle to show where the outer boundary of the nested <svg> element is positioned onscreen, as shown in Figure 02.01.

Figure 02.01. A nested <svg> element whose outer boundary is indicated by the outer rectangle outline.

graphics/02fig01.gif

When used in this way, the nested <svg> element can be used as the container for an SVG visual component, which can be made up of many SVG elements, including animated elements.

The advantage of grouping SVG elements within a nested <svg> element is that all the coordinates and positioning of the grouped elements refer to the upper-left corner of the nested SVG element. Within the nested <svg> element, the positioning of the other SVG elements is maintained relative to each other. So, to move all the elements that make up the component, you simply alter the x and y coordinates of the nested <svg> element. The whole group relocates within the containing <svg> element with the relative positions of the elements within the nested <svg> element preserved.

A nested <svg> element can be created directly within another <svg> element, as you have just read. SVG also has an <image> element that allows separately written and saved SVG document fragments (what I call visual components) to be inserted or imported into another SVG document. At the time this book was written, the Adobe SVG Viewer (version 2.0) does not yet allow the importing of SVG document fragments in this way.

A nested <svg> element is a useful container element to group other SVG elements. Another option is the grouping <g> element.

The <g> Element

The <g> element is, like a nested <svg> element, provided so that you can group several SVG elements within it. A <g> element has one important facility that a nested <svg> element does not have: A <g> element can be transformed. Transformation is a powerful tool in SVG whereby either statically or in an animation the shape, size, or position, for example, of a group of SVG elements can be changed.

The following code allows you to rotate a pair of rectangles contained within a grouping <g> element through 360 degrees over a period of ten seconds. Don't worry about how the animation works; this subject is discussed in Chapter 8, "Animation: SVG and SMIL Animation." Figure 02.02 shows the animation part completed. If the rectangles were created within a <svg> element, transforming them in this or any other way would not be possible. Thus, if you want to rotate, skew, or otherwise transform a group of SVG elements, you likely need to use the grouping <g> element.

Figure 02.02. The grouped rectangles, nested in a <g> element, are partway through a rotate transformation.

graphics/02fig02.gif

Listing 2.2 (GExample01.svg)
<?xml version="1.0" standalone="no"?>  <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"        "http://www.w3.org/TR/2001/PR-SVG-20010719/         DTD/svg10.dtd">  <svg width="500" height="400">  <g>  <animateTransform attributeName="transform"  type="rotate" values="0 150 100; 360 150 100"  begin="0s" dur="10s" />  <rect x="1" y="1" width="298" height="198"  style="stroke:red; stroke-width:2;  fill:none;"/>  <rect x="50" y="50" width="200" height="100"  style="fill:#EEEEEE;  stroke:blue;"/>  </g>  </svg> 

Like <svg> elements, <g> elements can have associated <desc> and <title> elements (see the sections on the <desc> and <title> elements later in this chapter). These elements provide information that can be useful when any later amendments are made to the code and also can be used to promote Web accessibility.

A <g> element can have an ID attribute to uniquely identify it within an SVG image. The <desc> element can be used to provide descriptive information about the purpose of the <g> element and its content, as in the following simple example of two groups of circles, each with transparent fill:

Listing 2.3 (idGs01.svg)
<?xml version="1.0" standalone="no"?>  <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"        "http://www.w3.org/TR/2001/PR-SVG-20010719/         DTD/svg10.dtd">  <svg width="500" height="400">  <desc>Two groups each of which contains two circles  </desc>  <g id="RedGroup" style="fill:none; stroke:red;  stroke-width:4;">  <circle cx="100" cy="100" r="50" />  <circle cx="200" cy="100" r="50" />  </g>  <g id="BlueGroup" style="fill:none; stroke:blue;  stroke-width:4;">  <circle cx="100" cy="250" r="50" />  <circle cx="200" cy="250" r="50" />  </g>  </svg> 

The ID attribute also can be used as the identifier for the target of an animation. Note in Figure 02.03 that the style information on the <g> element is applied to its child <circle> elements.

Figure 02.03. Two pairs of circles, each nested in a <g> element, inherit their style properties from the parent <g> element.

graphics/02fig03.gif

Just as <svg> elements can have other <svg> elements nested within them, <g> elements also can be nested within each other (as well as within <svg> elements).

Some Basic SVG Elements

Chapter 3 describes the SVG elements that define basic graphical shapes such as a rectangle and circle, as shown in previous examples that directly create a visual appearance onscreen. First, this section describes a number of other SVG elements that are not necessarily immediately visible onscreen but that are useful nonetheless.

The SVG <a> element, which functions similarly to the HTML/XHTML <a> element, is considered in Chapter 5, "Creating Navigation Bars."

The <desc> element

SVG container or graphics elements can contain a text-only description contained within a <desc> element. This description provides the opportunity to document a whole SVG document or image, or part of it, thus facilitating maintenance.

A <desc> element, when it is the child of the outer <svg> element, should precede any other child elements except for the <title> or <metadata> elements. This is suggested because future versions of SVG may impose stricter rules on element content than does the current DTD, presumably by using W3C XML Schema (although that is not stated in the SVG specification). Ordering of the <title>, <desc>, and <metadata> elements appears to be not of importance for rendering or accessibility.

Listing 2.4 shows how you might use the <desc> element to describe the rectangle you read about in Chapter 1, "The Basic SVG Tool Set."

Listing 2.4 (DescExample.svg)
<?xml version="1.0" standalone="no"?>  <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"        "http://www.w3.org/TR/2001/PR-SVG-20010719/         DTD/svg10.dtd">  <svg>  <desc>This image contains a simple square with a  transparent fill which will later  form the basis for an animated logo.  </desc>  <rect    x="10"    y="20"    width="100"    height="100"    style="fill:none; stroke:#000099; stroke-width:4;"/>  </svg> 

The <title> element

SVG container or graphics elements can contain a text-only title for the document or graphics object contained within a <title> element. This provides the opportunity to display information about the whole or part of an SVG document or image. An SVG viewer is not obliged to render the content of the <title> element but can do so; for example, as a tooltip or, as in the case of version 1 of the Batik viewer, in the title bar of the viewer. The Adobe Viewer does not yet display the content of the <title> element.

A <title> element, when it is the child of the outer <svg> element, should precede any other child elements other than <desc> or <metadata> elements. Ordering of the <title>, <desc>, and <metadata> elements appears to be not of importance for rendering or accessibility.

The <defs> element

The SVG specification encourages the reuse of code within individual SVG images or documents. This reuse is made possible by creating a definition of some element, or group of elements, within a <defs> element and then referencing that definition from another element in the main part of the SVG document.

Figure 02.04 shows an example of a linear gradient defined within the <defs> element, specifically within a <linearGradient> element (which is described further in Chapter 6, "Creating SVG Gradients"). The gradient is referenced using a bare names XPointer from a <rect> element.

Figure 02.04. An SVG linear gradient displayed by means of the <defs> element.

graphics/02fig04.gif

The code to render such an image is shown here.

Listing 2.5 (DefsExample.svg)
<?xml version='1.0'?>  <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"        "http://www.w3.org/TR/2001/PR-SVG-20010719/         DTD/svg10.dtd">  <svg width="800" height="600">  <desc>A simple use of the <defs> element to   contain the definition of a linear gradient.</desc>  <defs>  <linearGradient id="Gradient01" x1="0" x2="0" y1="0"  y2="150" gradientUnits="userSpaceOnUse">  <stop offset="20%" style="stop-color:#3300FF"/>  <stop offset="80%" style="stop-color:#CCCCFF"/>  </linearGradient>  </defs>  <rect x="100" y="50" width="300" height="100"  style="fill:url(#Gradient01)" />  </svg> 

Many other uses of the <defs> element are defined in the SVG specification. For example, SVG filters are defined within a <defs> element and then referenced using the filter property on an element that occurs later in the document. (This topic is described further in Chapter 7, "Using SVG Filters.") Many other SVG elements can be used singly or in combination, including linear or radial gradients, SVG filters and animations, and the linking <a> element. When combinations of elements are used to define a sophisticated shape nested within the <defs> element, the shape can be reused elsewhere in the document, thus reducing overall file size.

The <symbol> element

The <symbol> element can be used to create graphical template objects that can be used more than once in an SVG image by employing the <use> element (see the next section, "The <use> element"). A <symbol> element is similar to a <g> element except that a <symbol> element is not rendered, but instances of the <symbol> element created by a <use> element are rendered.

A <symbol> element possesses viewBox and preserveAspectRatio attributes to allow the graphic defined by the <symbol> element to scale to fit the rectangular space defined by the referencing <use> element.

The <use> element

The <use> element can reference a <symbol>, <svg>, <g>, <rect>, <line>, or other element to reuse the referenced element within an SVG image (the <rect> and <line> elements are discussed in Chapter 3). Typically, the ID attribute of the referenced element, whether it is a single graphics object or a container object, is the means by which the <use> object achieves an unambiguous reference.

One important difference between the <use> element and the <image> element (see the next section, "The <image> element") is that the image element can reference a whole external file, whereas a <use> element cannot.

I mentioned earlier that SVG provides several ways of supporting the com-ponentization of SVG so that you can think of parts of an SVG image as visual components.

In this section, you look at how you can make repeated use of simple, or not-so-simple, shapes within an SVG document. This example reuses a triangle defined within an SVG <path> element (which you meet in Chapter 3) contained within the <defs> element.

The triangle is defined in the <path> element in the following code, with the <path> element nested within a <defs> element:

<defs>  <path id="MyTriangle" d="M200 100 L300 300 100  300 Z" style="fill:#EEEEEE; stroke:red;" />  </defs> 

The triangle has a red outline and a pale gray fill. To go on to reuse that triangle shape you simply display three similar triangles one half-size, one normal-size, and one double-size by using the SVG <use> element three times but scaling each use by, respectively, 0.5, 1.0 and 2.0. This arrangement produces the half-size, normal-size, and double-size triangles. Don't worry about the detail of scaling at this stage; concentrate on the idea of code reuse.

The code for the half-size triangle looks like this:

<g id="HalfSize" transform="scale(0.5) translate(0,0)">  <use xlink:href="#MyTriangle"/>  </g> 

Use the grouping <g> element to contain the <use> element because the <g> element can be transformed. In this case, you simply scale the triangle by a factor of 0.5. The translate(0,0) is included so that you can see that you don't move the triangle at all, although when you look at Figure 02.05, you may think that you have. What has happened is that in the scaling by 0.5, the values of the points within the <path> element have also been multiplied by 0.5 and are therefore half as far from the origin of the coordinate system for the SVG image.

Figure 02.05. Three triangles, defined in the <defs> element and used in a <use> element, but scaled differently each time.

graphics/02fig05.gif

Listing 2.6 (TriangleTrans01.svg)
<?xml version="1.0" standalone="no"?>  <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"        "http://www.w3.org/TR/2001/PR-SVG-20010719/         DTD/svg10.dtd">  <svg>  <defs>  <path id="MyTriangle" d="M200 100 L300 300 100  300 Z" style="fill:#EEEEEE; stroke:red;" />  </defs>  <!--By specifying the ID, I can reference this graphic  later with the "use" element-->  <g id="HalfSize" transform="scale(0.5) translate(0,0)">  <use xlink:href="#MyTriangle"/>  </g>  <!--Here I have referenced My triangle by referring to  its ID in the xlink:href attribute. In the XLinks  section in Chapter 5, I describe this further. -->  <g id="NormalSize" transform="scale(1.0)  translate(0,0)">  <use xlink:href="#MyTriangle"/>  </g>  <g id="DoubleSize" transform="scale(2.0)  translate(0,0)">  <use xlink:href="#MyTriangle"/>  </g>  <!--In all three of the above groups, I have  transformed the same triangle by scaling it.  This allows for smaller file sizes.-->  </svg> 

Notice in Figure 02.05 that all aspects of the triangle have been scaled. In the double-size triangle, for example, you can probably see that the width of the outline is also twice as thick as the outline on the full-size triangle.

The <use> element, conceptually, causes a separate Document Object Model (DOM) tree to be created in memory. Because this element is not part of the DOM tree for the main part of the SVG image, access to parts of the element being referenced is limited. Also, functionality that can be achieved using SVG declarative animation or ECMAScript scripting is thus limited. In such circumstances, you may have to create separate instances of the element that would be referenced in order to create the desired animation or other effect. Thus, at least version 1.0 of the SVG specification has unfortunate limits on the reuse of elements for certain purposes.

The <image> element

The presence of the <image> element in an SVG document indicates that the content of an external file will be rendered into a rectangular area within the coordinate system of the referencing SVG image.

The <image> element can reference bitmap graphics files, such as PNG, GIF, or JPEG files. In addition, an important factor for the concept of visual components discussed throughout this book is that the <image> element also allows the importing of graphics files with the content type text/xml+svg (another SVG document or document fragment). Thus, a visual component created and saved in a file can be imported when needed.

An <image> element has x, y, width, and height attributes that define a rectangular area in which the bitmap or SVG image will be rendered. When an SVG file is being referenced, a new viewport is created with the boundaries of that viewport being defined by the x, y, width, and height attributes. The x and y attributes define the position of the upper-left corner of the viewport, and the width and height attributes define the dimensions within which the image is displayed. When an SVG file is being referenced, a separate DOM tree is created and properties from the referencing SVG image are not inherited by the referenced SVG image.

NOTE

At the time this book was written, the <image> element has been implemented in the Adobe SVG Viewer version 2.0 with respect to bitmap graphics, but not yet with respect to SVG images. This situation limits the scope for a significant aspect of SVG visual components, but you may not have to wait long before SVG files can also be accessed using the <image> element.

The <image> element is used with syntax such as the syntax used in the following code. Note the need for the x, y, width, and height attributes before the imported image can be appropriately rendered.

Listing 2.7 (ImageExample.svg)
<?xml version="1.0" standalone="no"?>  <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"        "http://www.w3.org/TR/2001/PR-SVG-20010719/         DTD/svg10.dtd">  <svg width="800" height="600">  <desc>This graphic links to an external JPEG image  </desc>  <image x="200" y="200" width="200px" height="150px"  xlink:href="NiceImage.jpg">  <title>A nice JPEG image.</title>  </image>  </svg> 

The <switch> element

The SVG <switch> element provides alternative rendering options if an SVG viewer is unable to render some aspect of content. When a <switch> element is activated, only one of the elements (or groups of elements) defined by the <switch> element is rendered. The <switch> element is particularly relevant if you employ SVG in a multinamespace context or using the <foreignObject> element because implementation is variable for the latter.

The <switch> element can also be used in multilingual SVG images or documents to control the text that is displayed according to the user's browser language settings, as you have read in Chapter 1. That use is described more fully in Chapter 17, "The Future of SVG".

Painter's Model

One of the important concepts about SVG that determines what you and your customers see onscreen is the rendering order for elements within an SVG image. The SVG term for this concept is the painter's model, in which the final rendering of an SVG image broadly resembles the way in which an oil painting is created. Just as when you apply oil paint to a canvas and cover up what is below it, you can obliterate (sometimes intentionally, sometimes not) other SVG elements rendered further back.

Typically, an element contained early in an SVG document is rendered toward the back and therefore is covered by paint applied as defined by later elements in the document.

Listing 2.8 illustrates how the painter's model works. The first <rect> element, which is pale bluish, is completely covered by the second <rect> element, which is red. However, because the third <rect> element is semitransparent, with an opacity of 0.5, some of the red color of the second <rect> element can be seen as in Figure 02.06.

Figure 02.06. Three rectangles illustrating the SVG painter's model. A rectangle later in a document covers the one preceding it. However, the lower-right rectangle is partly transparent, and some of the color of the middle rectangle shows through.

graphics/02fig06.gif

Listing 2.8 (PaintersModel.svg)
<?xml version="1.0" standalone="no"?>  <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"        "http://www.w3.org/TR/2001/PR-SVG-20010719/         DTD/svg10.dtd">  <svg width="300" height="400">  <rect x="30" y="30" width="100" height="100"  style="fill:#CCCCFF; stroke:none;"/>  <rect x="80" y="80" width="100" height="100"  style="fill:#FF0000; stroke:none;"/>  <rect x="130" y="130" width="100" height="100"  style="fill:#0000FF; stroke:none; opacity:0.5"/>  </svg> 

In practice, if you are using a program such as WebDraw or Illustrator to create your SVG graphics and you bring an object to the front, that action causes it to be placed later in the SVG source code and thus rendered toward the front of the SVG painter's model.

When you use grouping elements, such as the <g> element, it is as though you have created a separate canvas for rendering the group, and the result of that rendering is then applied to the parent canvas. This situation can have some subtleties, but for many practical purposes your drawing package takes care of the details.

SVG shapes can be painted along their outline, typically represented by a stroke property, or paint can be applied to the interior of a shape (it is filled), and the corresponding property is the fill property.

The SVG painter's model is considerably more complex than just described, but this short description suffices for most purposes in this book.

SVG Coordinate Systems

The coordinate system used in SVG is potentially complicated. You may want to skim or skip this section on your first read through the book and return to study it later. Understanding SVG coordinate systems isn't a straightforward process.

This section tries to help you understand some key points, which you use in examples in later chapters. If you want to make maximum use of SVG visual components as reusable graphics components, you need at least some understanding of the SVG coordinate system.

Earlier in this chapter, I showed you a nested <svg> element but didn't discuss in detail its impact. One implication is that a nested <svg> element opens a new coordinate system within it, which is responsible for the useful effect of being able to move whole graphics around while preserving their relative positions.

First, look at some of the jargon. SVG graphics are painted on the SVG canvas, which is potentially infinite in size. In practice, you or other users see only a finite rectangular portion of the SVG canvas, which is the SVG viewport.

Lengths in SVG can be expressed without specific units and are then said to be expressed in user units. Alternatively, a variety of units can be used with a value of any length, as shown in Table 2.1.

SVG allows a variety of transformations including rotation, skewing, trans-lation, and scaling that alter the coordinate system at the relevant part of an SVG document (or document fragment).

Table 2.1. Units of Measurement

Abbreviation

Meaning

em

The current font's font size

ex

The current font's x-height

px

Pixel

pt

Point

pc

Pica

cm

Centimeter

mm

Millimeter

in

Inch

%

Percentage

Establishing a new coordinate system

SVG allows for new coordinate systems to be established. Typically, that may be when a <svg> element is nested within an SVG document or document fragment. Suppose that you again have a simple rectangle nested within a <svg> element, which itself is positioned within another SVG element. Your source code might look like this (refer to Figure 02.01 for a visual reference):

Listing 2.9 (NestedSVG.svg)
<?xml version="1.0" standalone="no"?>  <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"        "http://www.w3.org/TR/2001/PR-SVG-20010719/         DTD/svg10.dtd">  <svg width="500" height="400">  <svg x="100" y="100" width="300" height="200">  <rect x="1" y="1" width="298" height="198"  style="stroke:red; stroke-width:2; fill:none;"/>  <rect x="50" y="50" width="200" height="100"  style="fill:#EEEEEE; stroke:blue;"/>  </svg>  </svg> 

The purpose of the red outline, represented by the first <rect> element, is simply to show the boundaries of the nested <svg> element. The second rectangle is to demonstrate the coordinate system within the nested <svg> element.

The red (outer) rectangle is positioned in the middle of the screen, yet because it has an x attribute of 1 and a y attribute of 1, you would expect it to be placed right at the edge. And it is. But it is placed at the edge of the new coordinate system created in the nested <svg> element that contains it so that the rectangle with the red outline shows in effect the position of the boundaries of the new coordinate system in the nested <svg> element. In that new coordinate system, the point (0,0) is in the upper-left corner of the red outline.

I use this technique of nesting <svg> elements frequently in this book. If you create a complex SVG graphic, with the relative positions of various SVG elements being important, you can preserve the relative positions of the elements and yet move the whole graphic around by simply altering the x and y attributes of the <svg> element within which you nest them.

If a transformation, such as a rotation, of the grouped graphic must be carried out, a <svg> element is not suitable you have to use a <g> element instead.

The viewBox attribute

Now move on to take a look at the viewBox attribute of the <svg> element. The SVG canvas is potentially infinite in size, and the view box gives you a window into that infinitely sized canvas. Often, you create graphics that are wholly displayed in the view box, but you can create SVG graphics anywhere on the canvas. If you are looking at a map created in SVG and want to travel east, for example, you would find that you need to see a part of the "infinite" map further to the right. You could do that by altering the SVG view box and looking at a part of the map further to the right. Look at the basics of how that concept works.

To illustrate how the viewBox attribute works, I adapt the nested SVG example from the preceding section. Note the viewBox attribute on the outer <svg> element in Listing 2.10.

Listing 2.10 (ViewBox01.svg)
<?xml version="1.0" standalone="no"?>  <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"        "http://www.w3.org/TR/2001/PR-SVG-20010719/         DTD/svg10.dtd">  <svg width="500" height="400" viewBox=" -70 -70  430 330">  <svg x="100" y="100" width="300" height="200">  <rect x="1" y="1" width="298" height="198"  style="stroke:red; stroke-width:2;  fill:none;"/>  <rect x="50" y="50" width="200" height="100"  style="fill:#EEEEEE;  stroke:blue;"/>  </svg>  </svg> 

The following line shows four values for the viewBox attribute:

<svg width="500" height="400"  viewBox=" -70 -70 430 330"> 

The first pair of numbers represents the x and y coordinates of the upper-left corner of the view box. The second pair of numbers represents the x and y coordinates of the lower-right corner of the view box. Thus, the lower-right corner of the view box shown in Figure 02.07 is (430,330).

Figure 02.07. The view box is altered so that the upper-left corner is at coordinates (-70, -70) and the lower-right corner is at (430,330).

graphics/02fig07.gif

You can check whether you have this calculation correct by counting out the values of the coordinates for the lower-right corner of the rectangle with the blue outline (the gray fill). The starting x is -70; the nested <svg> element is offset to 100; within that element, the x attribute is 50; and the width of that <rect> element is 200. Adding those numbers (70 + 100+ 50 + 200), you find that the lower-right corner of the blue outline rectangle has an x coordinate at 420. Similarly, the y attribute is at 70 + 100 + 50 + 100 = 320. Thus, the lower-right corner of the blue outline rectangle should be 10 pixels from the lower-right corner of the view box, which corresponds to what is shown in Figure 02.07.

With me, so far? It might help if I create an animation of the view box here so that you can look at it working. Here is the code:

Listing 2.11 (ViewBox02.svg)
<?xml version="1.0" standalone="no"?>  <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"        "http://www.w3.org/TR/2001/PR-SVG-20010719/         DTD/svg10.dtd">  <svg width="500" height="400" viewBox=" -120 -120  480 380">  <animate attributeName="viewBox" from="0 0 500 400"  to="-120 -120 480 380" begin="0s" fill="freeze"  dur="10s"/>  <svg x="100" y="100" width="300" height="200">  <rect x="1" y="1" width="298" height="198"  style="stroke:red; stroke-width:2;  fill:none;"/>  <rect x="50" y="50" width="200" height="100"  style="fill:#EEEEEE;  stroke:blue;"/>  </svg>  </svg> 

To fully appreciate what is happening, you need to run the code onscreen. The animation represents the transition from the original position of the nested <svg> to the one shown in Listing 2.11. It looks as though you have cut out a window in a playing card and are looking through it at the two rectangles. Then, you move the card with the window in it up and to the left, giving the appearance that the rectangles are moving down and to the right, although the rectangles are stationary. The window, or view box, is what is moving.

If you don't grasp the information in this section immediately, don't worry about it. You don't need to understand it to move on to later chapters, but you may need to understand it when you begin creating some of your own, more advanced, SVG images.

Stretch to fit

SVG provides the means for you to create images that stretch to fit the available space.

First, I show you the use of percentages as the size of SVG elements within an SVG image. Figure 02.08 shows an example.

Figure 02.08. Each of the four rectangles shown is 50 percent of the size of the SVG view box. When the view box is resized, so is each rectangle.

graphics/02fig08.gif

Here is the code that produced the figure:

Listing 2.12 (StretchToFit01.svg)
<?xml version="1.0" standalone="no"?>  <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"        "http://www.w3.org/TR/2001/PR-SVG-20010719/         DTD/svg10.dtd">  <svg width="50%" height="50%">      <rect x="0%" y="0%" width="25%" height="25%"  style="fill:blue"/>      <rect x="25%" y="0%" width="25%" height="25%"  style="fill:green"/>      <rect x="0%" y="25%" width="25%" height="25%"  style="fill:red"/>      <rect x="25%" y="25%" width="25%" height="25%"  style="fill:yellow"/>  </svg> 

Notice that the values of all the x, y, width, and height attributes are defined as percentages. The <svg> element is always half the height and width of the browser window. Similarly, each colored rectangle is always half the width and height of the SVG view box and is therefore a quarter of the width and height of the browser window. To see this effect in action, you need to experiment with the browser window size and watch the dimensions of the rectangles change.

This technique can be useful when you are creating, for example, entire SVG Web pages (see Chapter 12, "Creating a Simple SVG Web Site"). If you set the width and height of the <svg> element to 100 percent and create a <rect> element as the first element with width and height attributes of 100 percent, you have a uniform colored background that is resized as you resize the browser window.

SVG provides a technique that is useful when you don't know or don't control the size of the space in which an SVG image will be displayed.

Now, I use the viewBox attribute from the preceding section in a different way.

WARNING

When you set preserveAspectRatio to none , you may find that the stretch-to-fit feature produces unacceptable distortion of your original image.

Listing 2.13 (StretchToFit02.svg)
<?xml version="1.0" standalone="no"?>  <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"        "http://www.w3.org/TR/2001/PR-SVG-20010719/         DTD/svg10.dtd">  <svg width="300px" height="200px"  viewBox="0 0 600 400" preserveAspectRatio="none" >  <desc>This example uses the viewBox  attribute to automatically create an initial user  coordinate system which causes the graphic to scale  to fit into the viewport no matter what size the  viewport is.</desc>  <rect x="0" y="0" width="600" height="400"  style="fill:#990066" />  <circle cx="300" cy="200" r="150" style="fill:white;  stroke:red;  stroke-width:6;"/>  <text x="200" y="200" style="font-size:30;  font-family:Verdana">  Stretch to fit  </text>  </svg> 

The code produces the appearance shown in Figure 02.09.

Figure 02.09. The SVG image fits the view box by virtue of the viewBox attribute. If the view box is redimen-sioned, the image changes its dimensions to fit.

graphics/02fig09.gif

Try changing the width and height attributes of the <svg> element to 600px (pixels) and 400px, respectively, without changing anything else in the code. The circle and text resize to fill the defined space.

In Listing 2.13, you set the preserveAspectRatio attribute to a value of none. Whatever the dimensions of the width and height of the <svg> element, the contents then fill it. If you choose a shape with a lesser height, it is still resized, but the shape is distorted. If the code is as shown in Listing 2.14, you get the appearance shown in Figure 02.10.

Figure 02.10. The circle and text are resized to completely fill the allowed space because the preserveAspectRatio attribute is set to none.

graphics/02fig10.gif

Listing 2.14 (StretchToFit03.svg)
<?xml version="1.0" standalone="no"?>  <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"        "http://www.w3.org/TR/2001/PR-SVG-20010719/         DTD/svg10.dtd">  <svg width="600px" height="100px"  viewBox="0 0 600 400" preserveAspectRatio="none" >  <rect x="0" y="0" width="600" height="400"  style="fill:#990066" />  <circle cx="300" cy="200" r="150" style="fill:white;  stroke:red; stroke-width:6;"/>  <text x="200" y="200" style="font-size:30;  font-family:Verdana">  Stretch to fit  </text>  </svg> 

However, if you want for some reason to preserve the relative dimensions, or aspect ratio, of the SVG image, you can choose from a large number of options. Listing 2.15 preserves the aspect ratio and aligns the graphic with the left edge of the view box.

Listing 2.15 (StretchToFit04.svg)
<?xml version="1.0" standalone="no"?>  <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"        "http://www.w3.org/TR/2001/PR-SVG-20010719/         DTD/svg10.dtd">  <svg width="600px" height="100px"  viewBox="0 0 600 400"  preserveAspectRatio="xMinYMax meet" >  <rect x="0" y="0" width="600" height="400"  style="fill:#990066" />  <circle cx="300" cy="200" r="150" style="fill:white;  stroke:red; stroke-width:6;"/>  <text x="200" y="200" style="font-size:30;  font-family:Verdana">  Stretch to fit  </text>  </svg> 

As you can see in Figure 02.11, the aspect ratio is preserved, but much of the available space is not used.

Figure 02.11. The preserveAspectRatio attribute is used to preserve the relative dimensions of a resizable image and to align it with the left edge of the available space. The many other possible values for the preserveAspectRatio attribute are listed and described in Chapter 7 of the SVG specification.

graphics/02fig11.gif

The entire SVG coordinate system has a considerable number of complexi-ties, other than as described in the preceding short summary. However, it suffices for the purposes of this book. If you need more detailed information, a full description is in Chapter 7 of the SVG specification.

Fonts

SVG can be used for the presentation of both free-standing blocks of text (which are displayed similarly to HTML text) and text that partly forms graphics. In both types of uses, the graphic designer must have control over the appearance of the text onscreen.

For these types of situations, a designer needs to know that the chosen font, or something similar to it, is available to create the desired visual appearance whether or not that font has been installed on the user's computer. One option is to use the font-family property to specify a list of fonts, in the order of most desirable first, which the SVG viewer should use to render the applicable text.

However, on some occasions, particularly if a specific artistic appearance is sought, the display of a particular font may be particularly important .

To achieve such a predictable appearance, SVG makes use of the WebFonts facility, defined in the Cascading Style Sheets, Level 2 Recommendation from the W3C. For full information, see the CSS2 Recommendation at http://www.w3.org/TR/1998/REC-CSS2-19980512.

WebFonts

In one possible scenario, an SVG authoring tool may generate the parts of the WebFont relevant to the characters used within an SVG document. When used in a Web site, the file is likely to be stored in some suitable directory relative to the page being viewed.

However, a common problem with several aspects of CSS is that implementation is either patchy or inconsistent between available user agents (Web browsers or other viewing devices). To overcome the likely display inconsis-tencies that are possible when using WebFonts, the SVG specification defines SVG fonts that all conforming SVG viewers must support.

SVG Fonts

At its simplest, an SVG font is a font defined using an SVG <font> element. SVG fonts are designed to be used in display-only environments. In part, this approach seems designed to protect the intellectual property and, therefore, the income stream of companies that create fonts. If the font is legitimately installed on the authoring machine, the SVG font can be displayed to all who view the SVG image. However, the SVG font system doesn't allow editing of the SVG document on another machine if the font is not legitimately installed on it.

SVG fonts, either a full character set or a selective set including only those used in a particular SVG document or image, can be created automatically. For example, you can use the program svgfont to convert TrueType fonts to SVG fonts. Access further information and a download at http://www.steadystate.co.uk/svg/.

NOTE

Delving deeper into fonts requires understanding a little more of the jargon. A glyph is the way a character is presented onscreen. Much of the time, a one-to-one mapping occurs from a character to the corresponding glyph. For example, the uppercase form of the first character of the English alphabet in the font being used on this page looks like this: A. However, that same character can be displayed using a range of serif or nonserif or cursive fonts. The display appearance then changes, but the same character is referred to.

Why tell you about glyphs? A font is a collection of glyphs that typically share some common visual features. They may all lack a serif (a short stroke at the bottom of certain letters, like l or i), or the relevant letters may all possess a serif. Well-known sans serif fonts (those that lack a serif) are Arial and Helvetica. Commonly used serif fonts include Times Roman and Times New Roman.

In this chapter, I have introduced you to some of the basic structure of an SVG document, to provide you with a foundation for understanding the framework of an SVG image. Move on to Chapter 3 and take a look at the basic SVG graphic shapes.

CONTENTS


Designing SVG Web Graphics
Designing SVG Web Graphics
ISBN: 0735711666
EAN: 2147483647
Year: 2001
Pages: 26

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net