PH055-Pearlman.book Page 1 Monday, December 23, 2002 6:58 AM

1

Introduction to SVG

IN THIS CHAPTER

Standards: JPG, GIF, PNG, and SVG • Advantages of SVG •SVG and Browsers •SVG and Viewers •XML and SVG

VG (Scalable ) is a language S based on XML (Extensible Markup Language) for creating two-dimensional images on the Web. It is both vector- and text-based, combining graphics with programming to control Web images in a way not pos- sible through bitmapped graphic standards such as JPGs, , and PNGs. SVG is a subset of XML, which is rapidly becom- ing the foundation for all modern Web applications, including Microsoft’s .Net platform and other plat- forms by Sun and IBM. Getting to know SVG now will keep you on the cutting edge of Web development! SVG, with its animation and interactive capabilities, is well poised to become the future of Web graphics.

1 PH055-Pearlman.book Page 2 Monday, December 23, 2002 6:58 AM

2 Chapter1•Introduction to SVG

SVG is also a World Wide Web Consortium (W3C) stan- dard, which allows it to integrate with other W3C standards. For the Web developer, this makes it very easy to incorporate SVG into Web sites and helps to ensure compatibility. In this chapter, we will introduce you to SVG and tell you a little bit about its advantages as a graphics standard, how it compares with similar Web technologies, such as Flash, how browsers deal with SVG, and some of SVG’s important capa- bilities. We will also discuss current and future options for viewing SVG and will cover downloading Adobe’s SVG viewer. A viewer is essential for looking at SVG graphics at this time, because browser support for it is limited. We will also show you a bit about XML, SVG’s parent lan- guage, and we finish the chapter by creating and modifying our first SVG graphic file. So let’s get started!

Graphics Standards: JPG, GIF, PNG, and SVG

Bitmap Graphics

Most graphics you see on the Web are bitmap (also called ras- ter) images. Bitmap images are basically thousands of tiny pix- els, each of which carries information about color. A pixel is like a tiny dot. If you’ve ever looked at a television screen or a magazine image up close, as demonstrated in Figure 1–1, you’ve seen that the image looks as though it is made up of a lot of scintillating little dots. Those are pixels. Because most display devices (such as monitors) are raster devices, a bitmap or raster image just needs to be uncom-

FIGURE 1–1 bitmap.. Bitmapped image is made up of pixels. Pixels look like tiny dots when viewed close up. This gives bitmap graphics their “jagged” edges. PH055-Pearlman.book Page 3 Monday, December 23, 2002 6:58 AM

Graphics Standards: JPG, GIF, PNG, and SVG 3

pressed to be viewed onscreen. Some common bitmap graphics used on the Web are: • GIF (Compuserve Graphics Interchange Format), a lossless compression format. A lossless format does not lose data when compressed. GIFs were created to be relatively small in bandwidth and are still the most popular bitmap graphic format on the Web. Unfortunately, their quality is usually not great, as you can see by browsing enough Web sites! • JPG or JPEG (Joint Photographic Experts Group), a lossy compression format. Lossy formats lose data when com- pressed. JPGs were created specifically for photographic images or images that require a lot of detail. They work by saving a complete black and white version of the image and some of the color information. JPGs are called a lossy format because they lose some color data in order to save on file size. • PNG (Portable Network Graphic), a lossless and well- compressed format created to solve some of the draw- backs of GIFs and JPGs. Because they are lossless, they result in somewhat better resolution than JPGs, but they are often much larger in file size. As anyone who surfs the Net knows, when you see images on the Web, there is usually a real tradeoff between quality and download time. High-resolution bitmapped images take for- ever to download on a slow connection, but faster, lower reso- lution bitmapped graphics are usually pretty low in quality. Also, bitmapped images do not scale well, which means that if a bitmapped image is scaled to a larger size, at some point it will lose resolution and crispness because its pixels will increase in size, giving it a bumpy, jagged look (Figure 1–2).

FIGURE 1–2 On the left, we see a JPG image of a cube, on the right we see it scaled up. Notice the bumpy, fuzzy look. PH055-Pearlman.book Page 4 Monday, December 23, 2002 6:58 AM

4 Chapter1•Introduction to SVG

Vector Graphics

Vector images are based on mathematical formulae and a coor- dinate system. Therefore, they are not limited according to pixel size, as are bitmapped graphics. Remember plotting points on a graph in high school algebra? Vector graphics use a similar coordinate system to create shapes. Roughly, a vector image takes a series of coordinate points plotted on a graph and contains instructions to the browser on how to render those points as an image, using curves, straight lines, etc. Vector graphics have many advantages over bitmapped graphics. They scale well, retaining their resolution at any size and with any change of the viewing device. This is especially important with the wide variety of screen sizes and devices, such as cell phones and PDAs! Take a look at a vector image of a cube, shown in Figure 1– 3. On the left, the cube is small, and on the right, the same vec- tor cube is scaled up to a comparable size with the JPG file in Figure 1–2, which is an image that loses resolution signifi- cantly. Note that, because vector graphics are based on mathe- matical formulae, the increase in size means that the formulae are multiplied in proportion, and the shape still redraws and renders crisply.

FIGURE 1–3 On the left is a vector image of a cube, and on the right it is blown up several times. Note that the resolution stays pretty much the same.

Most bitmapped graphics, in addition to not scaling very well, often render differently on different client browsers. (The exception to this is the PNG graphic format, which uses gamma correction to control its own brightness and will, there- fore, render the same on different browsers.) This can cause PH055-Pearlman.book Page 5 Monday, December 23, 2002 6:58 AM

Advantages of SVG 5

difficult design issues, because an image may look one way in Internet Explorer (IE) 4 and another way in Netscape 6. Bitmap images are also relatively large in bandwidth. A bitmapped image with a high resolution will be a very large file when compared with a similar vector image, which will be a much smaller file. Of course, this is not to say that we can just get rid of bit- maps on the Web altogether. Bitmapped images continue to be necessary. Photographic material, for example, cannot be ren- dered adequately by vector formats, so don’t toss out all your JPGs! Fortunately, you can embed inline JPEG or PNG graph- ics in SVG files, so you’re by no means limited to vector art. This makes the creation of sophisticated graphics with SVG quite easy.

Advantages of SVG Besides being resolution-independent and using less band- width, SVG has a number of other advantages over other graphics standards. One big one is that it uses a “color profile” to render colors more accurately, regardless of browser and monitor differences (even rendering accurately to devices such as PDAs and cell phones). As anyone who has been frustrated by color differences between IE and Netscape can tell you, this is a significant advance for graphics on the Web! We’ll cover some of SVG’s color capabilities in Chapter 5. Some of SVG’s many advantages are listed below. SVG is: • Text-based • Open source • Written in XML • An official W3C graphics standard • Accessible for people with visual disabilities • Searchable • Dynamic and updateable • Cross-browser compatible In addition, SVG: • Can be animated • Supports filters, transformations, clipping, and masking PH055-Pearlman.book Page 6 Monday, December 23, 2002 6:58 AM

6 Chapter1•Introduction to SVG

• Supports transparency • Text can be selected, copied, spoken by the computer, or indexed. • Can be exported from Illustrator, CorelDRAW, WebDraw, etc. • Can be exported from Geographics Information System (GIS) software • Can be used for print as well as Web graphics Text-based simply means that SVG, unlike most graphics standards, is coded with simple text. Most graphics standards use binary code, readable only by computers. Text-based code is readable and editable by human beings like you and me. Open sourced means that you don’t need to buy any expensive soft- ware in order to use SVG. All you need is a simple text editor, such as Notepad or BBEdit, to create and edit SVG graphics. Because SVG code is text, search engines can index SVG graphics according to what the diagram contains, (such as “image of red circle”), and SVG graphics can be made accessi- ble to people with visual disabilities by means of voice or Braille software, which can use the text description to describe the image. Because SVG is XML-based, it can (using Perl or Java to convert the data to SVG) render graphics from database data, so images can dynamically update. In other words, your site can contain graphics that change according to the data that is being retrieved. A weather map done in SVG is a good exam- ple of this capability. SVG graphics can easily be animated, made interactive, and styled with CSS and XSL stylesheets. These attributes take SVG’s capabilities beyond the scope of any previously existing graphic standard.

SVG versus Flash

When most people think of Web animation, they think of Mac- romedia’s Flash. However, SVG is just as easy to animate because many animation capabilities are written into its code. In fact, many similarities exist between Flash and SVG, such as: PH055-Pearlman.book Page 7 Monday, December 23, 2002 6:58 AM

SVG and Browsers 7

• Both SVG and Flash (.swf) files are vector-based. • Both SVG files and .swf files can be animated. • Both currently require plug-ins to view images. However, browsers will soon have SVG viewing capability. • Both SVG and .swf files can be zoomed and panned. • Both SVG and .swf files can contain sound. However, sound is not currently part of SVG’s specifications. • Both are scriptable, though Flash’s Actionscript is propri- etary. SVG can be scripted with Javascript, Java Bindings, and ActiveX controls. • Both allow hyperlinking. • Both have database connectivity. So why use SVG? Well, it turns out that SVG has some very distinct advantages over Flash. First, SVG is open-. This means you can easily see, read, and edit the code underlying an SVG image. Flash’s code is proprietary, or owned by , and therefore is hidden from public view. Viewing Flash code wouldn’t do most of us much good anyway, because it is written in binary format, which consists of strings of zeros and ones—not of great use to most flesh-and-blood-based life forms! Which brings us to the second advantage of SVG—it is text-based. So, it is easy to read an SVG file and easy to create one. To make or edit a Flash file, you must have access to Flash software, and even then, you won’t be able to read what’s really going on under the hood. However, despite these comparisons, Flash and SVG are not direct competitors. SVG’s basis as a subset of XML gives it the ability to do things that Flash can’t, such as coordinate seamlessly with other Web standard technologies. Flash is a proprietary, binary-coded application used primarily for Web animation, which it does quite well.

SVG and Browsers SVG doesn’t currently have native browser support in any of the most popular browsers (such as Netscape, IE, or Opera), so SVG viewing is limited to plug-ins for the time being. How- PH055-Pearlman.book Page 8 Monday, December 23, 2002 6:58 AM

8 Chapter1•Introduction to SVG

ever, both Netscape and IE are promising future browser sup- port for SVG, and with browser support, the plug-in will eventually be phased out. There are a couple of open-source browsers that offer some support for SVG. The SVG-enabled Mozilla has support for a lot of the SVG specification (but not all of it). For information, check out www.mozilla.org/projects/svg/. The X-Smiles project (www.x-smiles.org/) is a Java-based effort to include native sup- port for SVG in a browser and W3C’s own Amaya, which is a browser/editor, and offers some support for SVG, although its support is by no means complete.

SVG and Viewers Because SVG has little current native browser support, to view SVG files, you must download an SVG viewer. There are numerous SVG viewers out, but by far the most popular is the Adobe SVG viewer. The viewer is free and can be downloaded by going to www.adobe.com/svg/viewer/install/main.html. The Adobe viewer works with IE 4 and above and with Netscape 4.5 through 4.77.

NOTE: Browser Issues: Netscape and Opera At the time of this writing, Netscape 6, 6.01, and Opera 5 were not officially supported in the Adobe SVG viewer. For information and updates on how to use Adobe’s SVG viewer with the above browsers, please check out www.adobe.com/svg/.

In addition to the Adobe SVG viewer, the Batik project offers an open-source code viewer, as well as an SVG toolkit, at http://xml.apache.org/batik/. IBM also has an SVG viewer avail- able at www.alphaworks.ibm.com/tech/svgview. An exciting facet of SVG is that it can be rendered as easily on pocket devices as on desktop PCs. The CSIRO Pocket Viewer has an evaluation version of its SVG viewer for pocket PCs on its site. Just go to www.cmis.csiro.au/sis/SVGpocket.htm for an overview and information. PH055-Pearlman.book Page 9 Monday, December 23, 2002 6:58 AM

XML and SVG 9

Once you have downloaded the SVG viewer of your choice (Adobe is recommended for this book), you’ll want to see some real-life SVG to get an idea of its capabilities. Point your browser to (www.phptr.com/advancedweb/svg) to view an SVG file. If your Adobe SVG viewer is downloaded properly, you should see the image in Figure 1–4.

FIGURE 1–4 The image and code are named jasc.html and are located at www.phptr.com/ advancedweb/svg. This file was created in Jasc WebDraw, which is an SVG editor and drawing package. We’ll tell you all about Jasc in Chapter 10. The SVG content was then embedded into an HTML page.

XML and SVG We’ve talked a lot about how SVG is written in XML, based on XML, etc., and you’re probably wondering whether you need to know XML to write or edit SVG code. In fact, SVG is a type of XML, and knowing a bit of XML document structure and syntax will help you to understand the logic, conventions, and limitations you might encounter in SVG. In this chapter, we give you a little taste of XML. If you really get interested, we go further into XML in Chapter 10. So, what is XML? XML is an extensible and flexible markup language. What does that mean? Let’s find out. PH055-Pearlman.book Page 10 Monday, December 23, 2002 6:58 AM

10 Chapter1•Introduction to SVG

WHAT IS MARKUP? HTML (Hypertext Markup Language) is an example of a markup language that you may be familiar with. In an HTML document, if you run across something that looks like this:

you know that it is a markup tag that indicates a new para- graph. HTML has built-in markup tags, which are mostly for formatting, such as

for paragraph and for bold. HTML markup tells browsers, processors, and editors how to format and organize content. It consists of start and end tags, processing instructions, etc. Markup describes content. Notice the angle brackets around the

. A good way to think of markup is that anything between angle brackets is markup . Anything described by that markup is content.

This is content

WHAT IS EXTENSIBLE? So what about XML? Well, like HTML, XML has two types of building blocks, markup and content. Content is the character or image data that resides inside the markup. What makes XML so different and so powerful is that, unlike HTML, which comes with built-in markup tags, XML is extensible, which means that you can define your own markup. That means the potential for creating markup is relatively unlimited, or extensi- ble. You can create markup that describes tags in your own doc- ument rather than being limited to the tags that HTML gives you. Or you can use preset definitions, called DTDs, or docu- ment type definitions. For now, let’s take a look at some really basic XML code (Example 1–1).

EXAMPLE 1–1 1. 2. 3. My first experiment 4. This is fun 5. PH055-Pearlman.book Page 11 Monday, December 23, 2002 6:58 AM

XML and SVG 11

This is a very simple XML document. What do we see here? 1. The processing statement, or XML declaration. We’ll go into this a little later in the chapter. 2. An opening tag named that we created. That means we did not get it from any other source than ourselves. 3. An opening tag named that we created, content for that tag (My first experiment), and closing tag. 4. An opening tag named that we created, con- tent for that tag (This is fun), and closing tag. 5. Closing tag.

ELEMENTS So what are all these opening and closing tags about? Well in XML, we build documents with elements. An element has an opening tag, , and a closing tag, . The element includes the tags and what is in between them. In the above code snippet, My first experiment and are the opening and closing tags, and My first experiment is the entire title element. Note that a closing tag differs from an opening tag in that it has a forward slash (/) inserted into it before the tag name. In the above code snippet, the element is the root element. Every XML document needs one root element. The root element contains the other elements inside of it. Another way of saying this is that the other elements are nested within the root element . Some basic markup symbols and their uses are listed in Table 1–1.

TABLE 1–1 Some Basic XML Markup Symbols

SYMBOL USE

? begins and ends a processing instruction < delimiter that starts the beginning of a tag > delimiter that ends a tag

12 Chapter1•Introduction to SVG

Processing Statement: Now to get to that mysterious first line of code: This line of code is the XML declaration. It is part of the pro- log for the XML document. It must contain the version number but can also contain other instructions, such as targeting a spe- cific character set (see Chapter 12 on Unicode) or stating whether the XML document is standalone (which means it “stands alone” or does not reference an external document) or whether it is not standalone (it references an external docu- ment). This is particularly important to note because most SVG documents reference an external document, usually the W3C standards body on SVG. The above code statement is known as a processing instruc- tion because it tells the computer to do something. In this case, it tells the browser and related software that this is an XML file and what version of XML it is. At this writing, there is only one version of XML, but in the future that is sure to change! Pro- cessing instructions use angle brackets and question marks to begin and end the line of pro- cessing instruction code.

Well Formed or Valid? An XML document can be well formed only or both well formed and valid. What does this mean? Let’s look at well-formed doc- uments first. For an XML document to be well formed, it must follow some simple syntax rules: • Each opening tag must have a corresponding closing tag. • XML is case-sensitive; thus, , <Title>, and <TITLE> are all three different tags. • There must be at least one element in a well-formed XML document. • There can be only one root element. • Elements and their tags must nest correctly. • Element names must conform to the following naming rules: ◗ They must start with a letter or an underscore PH055-Pearlman.book Page 13 Monday, December 23, 2002 6:58 AM</p><p>XML and SVG 13</p><p>◗ They can contain letters, digits, periods (.), underscores (_), or hyphens (-). ◗ Whitespace is not allowed. ◗ They cannot begin with the sequence xml. Unlike HTML, XML is completely and, unfortunately, totally unforgiving of syntax and space errors. Triple-check your XML code. XML is case-sensitive, so pick one style of naming, using either all or no caps, and stick with it. By con- vention, XML tags are usually written in lowercase. All XML parsers check to make sure that start and end tags exist and check delimiters and characters, as well. Well formed means the document and syntax structure is correct, according to the above bulleted list. Let’s experiment with this now. Open a simple text editor, such as Notepad for Windows or BBEdit for Macs. Type in the following code, exactly as you see it:</p><p><?xml version="1.0"?> <document> <title>My first experiment This is fun

Now save the file to your hard drive with a name such as myfirst.xml, making sure you save it with the .xml extension. To do this in Windows, you will need to change the file type drop- down to All Files. It is important to save this as an .xml file; otherwise, you won’t be able to see it as XML code. We saved our file as myfirst.xml. Now open a browser window, either by connecting to the Internet or choosing Work Offline. Either click File, Open, Browse and find myfirst.xml in your own drive path specifica- tion or type in the file path in the location bar. If you open the file in IE, you will see the code colored to denote syntax (Figure 1–5, left). Congratulations! You have a well-formed XML document! PH055-Pearlman.book Page 14 Monday, December 23, 2002 6:58 AM

14 Chapter1•Introduction to SVG

NOTE: If you open the file in Netscape, you will see the text content alone, without the markup (Figure 1–5, right). This is correct; you are still on track. Netscape doesn’t show the code tree the way IE does.

FIGURE 1–5 The left image is myfirst.xml in IE 5; the right image is myfirst.xml in Netscape 6.

Now let’s see what happens when we deliberately make a mistake in coding. Go to your Notepad file and delete the clos- ing tag. Save the file as myFirstError.xml, again making sure that you save it with the .xml extension. Now open the file in a browser and see what happens. Note that you get an error telling you exactly what you did wrong in both Netscape and IE! Pretty darned cooperative, aren’t they? Sometimes fixing errors is that easy, sometimes not. Often, you have to hunt around a bit for what you did wrong in the code. Usually in IE 5 or Netscape 6, you will get at least a line number where the error is supposed to have occurred. Now, put back the tag to end the code prop- erly. Save and view it. All is well. Now let’s get adventuresome here. Let’s add another ele- ment. Open your file in your text editor of choice and, after the code line: My first experiment Press Enter and type in: PH055-Pearlman.book Page 15 Monday, December 23, 2002 6:58 AM

XML and SVG 15

Jane Jones

Notice that we’ve added a new element, but that some- thing is different here. This new element, author, has two ele- ments nested within it: firstName and lastName. Each nested element has an opening and closing tag, and the entire author element ends with the closing tag. This is an exam- ple of two elements (firstName and lastName) nested within the element author. The element author contains the two ele- ments firstName and lastName. In XML, we say that author is the parent element of firstName and lastName, and that first- Name and lastName are child elements of the element author.

NOTE: With nested elements, each child element must begin and end completely within the parent element.

We’re going to add one more thing—a comment. A com- ment is a piece of code that does nothing, it is there only for you to describe or notate the code. It is quite useful to comment your code, because often you will do something in the code and forget about why you did it! It is also very helpful when viewing another person’s code to be able to see his or her com- ments. A comment looks like this: Open up your file again, and, below the line of code: My first experiment Type in: Save the file, and view it as usual. You will see that, in Internet Explorer, you can see the comment as part of the code, but in Netscape, you still see only the content of the code, not the markup or comment. PH055-Pearlman.book Page 16 Monday, December 23, 2002 6:58 AM

16 Chapter1•Introduction to SVG

If you want, play around with this code some more until you get comfortable with the “well-formed” concept. You can edit a Notepad file while it is open. Just remember to save it by going to File, Save. Play around! Try adding an element or two or some other content. To view the newly edited version in IE or Netscape, just click the Refresh button on the toolbar after saving your file. This will reload the updated file. Now that you’re pretty comfortable with well-formed doc- uments, we’re going to up the ante a little bit. Most XML docu- ments need to be valid in addition to being well formed. What defines a valid XML document? Quite simply, a valid XML doc- ument must include a reference to a DTD.

DTD

An important aspect of XML structure is the XML DTD. To understand the DTD a bit, let’s go back to our HTML example. HTML code contains a lot of markup that is already defined, such as our favorite,

. How does HTML know that

means to start a new paragraph? Simple, that information is defined in HTML’s DTD. HTML’s DTD tells the parser to start a new paragraph every time it runs across

. As we said before, XML is extensible. That means that we define our own elements and markup, and it also means that we must define our own DTD for our XML documents. The DTD file holds all of the allowable parameters for the XML file that references it. All valid XML files must have a DTD. Let’s say that you want to build a house. The blueprint of the “house” would be the DTD. The DTD defines what is and what is not allowed in the XML document that references it. This is like saying you are going to build a house and allow the following: doors, walls, a roof, and a floor. (Of course, this is way too skimpy for a real house, but you get the idea.) So the door element would be one of the elements in the house, defined by us. Once a DTD is named and the elements are specified, you can define specific characteristics of those elements, which are called attributes. Attributes can describe color, height, width, etc. An attribute of the door element in our house example PH055-Pearlman.book Page 17 Monday, December 23, 2002 6:58 AM

XML and SVG 17

might be wood, metal, glass, aluminum, or rubber. The attribute wood is, therefore, an attribute that we have just given the element door. So think of the DTD as the blueprint, an ele- ment as a door, and the element door’s attribute as wood. How does the valid XML document read the DTD? In one of two ways. The DTD can either be internal, which means that it is written into the XML document, or it can be external, in which case, you must include a reference to the external DTD. What does a DTD look like? The following is a partial example of how a DTD is set up. We are using our “house” example.

]>

We used the idea of house as the DTD. Obviously, a rabbit is not an allowable item in a blueprint of a house. A rabbit is an animal. So if our DTD is about a house, and we don’t want to include a rabbit in it, then in our valid XML file, we wouldn’t be able to include a rabbit. In other words, everything that appears in a valid XML document must be declared in a refer- enced or inline DTD. Note that the above code includes no attributes.

DTD CODE Take a look at the DTD code above. First, DOCTYPE is the document type declaration, not to be confused with the DTD, or document type definition. This begins the DTD file. Again, each element you are going to use for your XML document must be declared in the DTD that it references. The element declaration must start with an exclamation point (!), and the name of the element must start with a letter or under- score character. The ! defines the instruction to the browser or processor that this is an ELEMENT and not just a word. It is a good idea, though not necessary, to start the first ELEMENT PH055-Pearlman.book Page 18 Monday, December 23, 2002 6:58 AM

18 Chapter1•Introduction to SVG

statement with the same name as the DOCTYPE. ELEMENTS are written as !ELEMENT.

DTD ELEMENT TAGS

< Start delimiter Close delimiter /> Empty Tag (mostly used as a placeholder) !ATTLIST Attribute declaration (all caps necessary)

(#PCDATA) Parsed character data, (#PCDATA), tells the processor that characters are allowed in an ELEMENT, as opposed to ele- ments or other instructions to the computer. (#PCDATA) is most often used for text content. You must tell the processor what type of data is allowed in each ELEMENT statement. Is an image allowed? Is just text allowed? More than one type of data is allowed in an element, but it all must be declared. In the example above, in !ELEMENT house (which is a par- ent), we say that the elements doors, walls, roof, and floor (which are child elements of house) are allowed; then we break it down further by saying what can be included in each child element. We say (and this is only a partial list of the full state- ment) that in the !ELEMENTs doors, walls, roof, and floor, we can use text. Looks simple, right? Remember, we set up the parameters for our own documents, and we get to decide what we will include, but everything we use in our valid XML docu- ment must be declared in our DTD.

NOTE: (#PCDATA) (#PCDATA) is always enclosed in parentheses.

A DTD can be saved as a separate file from the XML docu- ment, then referenced in the XML document with a line of code, like so: PH055-Pearlman.book Page 19 Monday, December 23, 2002 6:58 AM

XML and SVG 19

That line of code references the house.dtd. SYSTEM refers to the fact that this particular DTD resides on your home sys- tem. If the DTD resides on the Web, PUBLIC is the identifier you would use in place of SYSTEM. The DTD can also be included in the XML document as an “internal” DTD.

ADDING A DTD TO MYFIRST Open up Notepad for Windows or BBEdit for Macs, and reopen your myfirst.xml file. Type or copy in the following after the XML declaration (remember what that was?). It was the line of code that looks like this:

]>

Save the document again as myfirst.xml. Again, when sav- ing the document, make sure to use the .xml three-character extension and save it as type All Files, or it will be saved as a .txt document. In Windows 95/98, be careful to put quotes around it (“myfirst.xml”), or it will be saved as myfirst.xml.txt. Now view the file in a browser. You should see something similar to Figure 1–6 or Figure 1–7. PH055-Pearlman.book Page 20 Monday, December 23, 2002 6:58 AM

20 Chapter1•Introduction to SVG

FIGURE 1–6 myfirst.xml in Internet Explorer 5.

FIGURE 1–7 myfirst.xml in Netscape 6. PH055-Pearlman.book Page 21 Monday, December 23, 2002 6:58 AM

XML and SVG 21

Once again, if the code is colored in IE or if just the text shows up in Netscape, the document is well formed, but we want to find out whether it is valid, as well. How do we do that? To validate the document, you have to have a validating XML parser. IE 5 has a parser but you may have to download parts of it, depending on your operating system. If you don’t have a validating parser, there are some on the Web that let you paste in your code and tell you whether it is valid. One is located at www.stg.brown.edu/service/xmlvalid/. Simply paste in your code where you are given the “text” form, and press the Validate button. You will be returned to a page that tells you whether the document validates. If you have errors in the doc- ument, this program will also list them.

PARSERS An XML parser, including ones contained in some but not all browsers, check the framework and content of an XML state- ment for well-formedness; and, if they are validating parsers, they validate an XML file. Depending on the company, the pro- grams also allow extensive planning and editing. This is a developing field, and there are new products out constantly.

XML and SVG As we keep saying, SVG is written in XML, so familiarity with XML’s syntax is very helpful when you want to create or edit SVG code. Having already looked at XML code, let’s take a look at some simple SVG code. Using the Jasc WebDraw program (a drawing application for SVG, which we discuss further in Chapter 10), we made the following graphic in SVG (see Figure 1–8) and exported it into a raster bitmap file for the purposes of display in this book. PH055-Pearlman.book Page 22 Monday, December 23, 2002 6:58 AM

22 Chapter1•Introduction to SVG

FIGURE 1–8 triangle.svg drawn in Jasc WebDraw.

The code behind the SVG graphic is:

EXAMPLE 1–2 triangle.svg 1. 2. 4. 5. 7. 9. PH055-Pearlman.book Page 23 Monday, December 23, 2002 6:58 AM

XML and SVG 23

1. The first line shows the XML declaration, as we’ve already seen. But something new has been added— standalone. Standalone refers to whether the SVG doc- ument “stands alone,” i.e., it has no reference to an external file, or whether it does contain a reference to an external file. In the above case, standalone is set to “no”, so we have a reference to an external file—in this case, the actual DTD. 2. In our XML discussion, we talked a bit about the DTD. Well, in this SVG code, the second line and the third line refer to the SVG DTD. Notice that these two lines reference an external DTD. 3. Just where is that external DTD located? At the URL http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/ svg10.dtd. It is part of the W3C, the standards body of the Web. Here is the great news: SVG, unlike XML, has its own DTD already figured out by a team of experts, so it is not necessary to create a DTD for your SVG files. (And you thought this would be hard!) What does this DTD contain? All allowable SVG elements are defined in the SVG DTD, which resides at the W3C URL above. (For a complete list of SVG elements and attributes, see Appendices A and B. And, for the very brave, check out the W3C URL to see what the SVG DTD looks like. If you think you want to add elements or attributes to the SVG DTD, just take a look at the real thing!) 4. The SVG code actually begins with the ele- ment—which consists of the opening tag and the closing tag—and includes everything in the document. This is the root element. Width and height are attributes of the element, and they set the width and height of the SVG document (as you might have guessed). 5. Path is also an SVG element. In the above picture, the path is actually the red line going behind the triangle. The element here has two attributes: d and transform. The d attribute refers to path data, and the val- ues of d are what appear after the equal (=) sign. The numbers you see are x and y coordinates defining the PH055-Pearlman.book Page 24 Monday, December 23, 2002 6:58 AM

24 Chapter1•Introduction to SVG

path. Notice the letters M and L. These further define the path data. M means moveto, which tells the browser at which coordinates to start the line. L means lineto, which tells the browser where to draw the line. There- fore, M114.286 260 means moveto the coordinates 114.286 x and 260 y. L320 222.857 means draw a lineto coordinates 320 x and 222.857 y. We will be covering the path element in greater detail in Chapter 4 . The trans- form attribute is further defined by its value translate, which we won’t cover here but will cover in detail in Chapter 2 . 6. Style is yet another attribute of the element. The style attribute can be used to describe a lot of the pre- sentational aspects of our path. Our path element here defines just one single line, not a closed shape. Because the fill value refers to color inside of a shape, here we set the fill value to none because we don’t have a shape, only a line. So how do we color the line? The color of the line is described by the stroke value as the RGB number (171,17,17), which renders as red, and the width of the red line is set by the stroke-width value to be 5 pixels wide. The stroke and stroke-width values con- trol how the outline of a shape appears and/or how a line appears. Because here we have only a line and not a shape, stroke tells us how to color that line. 7. The next element we find in the code is the element. In SVG, polygon can be used to describe any closed shape made with straight lines. In this case, we’ve described a three-sided shape (yes, a triangle) by using the attribute points, then listing the x and y coordinates of the points of the triangle. How is this possible from this seemingly strange list of numbers? If you imagine a pen on paper, it’s as though the pen touches the paper on the first set of coordinates (211. 429 and 143.571). Where are those coordinates? Well, in SVG, as almost everywhere else, the convention is that you write the x coordinate first and the y coordinate second. So the pen touches the paper on coordinates 211.429 x and 143.571 y. Then our hypothetical pen draws a line to the second PH055-Pearlman.book Page 25 Monday, December 23, 2002 6:58 AM

XML and SVG 25

set of coordinates, 201.571 x and 400 y, then draws a line down to the last set of coordinates, 325.714 x and 97.1429 y. So far, we have only a two-sided, open angle, but there are no more coordinates. How does SVG know to close the line and make this a triangle? 8. Well, remember, we made this shape a polygon element. A polygon element is always a closed shape, so if we don’t provide a closing coordinate, SVG automatically draws a line from the last coordinate we define to our beginning coordinate to close the shape (Figure 1–9). If we had wanted an open angle here, we couldn’t have used the polygon element; we’d have to use another element, such as or .

FIGURE 1–9 The image on the left is drawn using the element, with three points specified. The image on the right is drawn using the element with three points specified. The element automatically closes the shape by adding a line from the last point back to the starting point.

Again, we use the style attribute to describe how our polygon shape is going to be colored. The style attribute again describes mostly the presentational aspects of the shape, rather than its structure. In this case, we’ve filled the polygon with blue by using an RGB number (0,0,255) as our fill value, and we’ve out- lined the polygon in black, again by using the RGB number for black (0,0,0) in the stroke value. We’ve set a thin outline by making the stroke-width value equal to one pixel. 9. The closing tag closes the root SVG element and the document. Note that, like XML, all opening tags must have closing tags, and the closing tag of the root element must be the one to close the file. PH055-Pearlman.book Page 26 Monday, December 23, 2002 6:58 AM

26 Chapter1•Introduction to SVG

CHANGING VALUES AND CODE It is helpful when learning SVG (as with any programming lan- guage!) to play around with the code. So open up your text edi- tor and type in the code for the above drawing:

Save the drawing to your hard drive as triangle.svg or something like that, and remember to make sure to save the file with the .svg extension; otherwise, it will save as a text file. View the file in your browser. We saved the file as triangle.svg.

NOTE: Make sure you have the Adobe SVG viewer downloaded and installed before you try to see your SVG files. Otherwise, they’ll just show up as code!

Let’s have some fun.

Challenge 1

1.1 First, save your work under a slightly different name, for example, tri- angleTest.svg, in case you make a mistake in coding and can’t get back to the original code. 1.2 In the new file, try changing the coordinates of the path element (the red line) to