Home > Articles > Web Services > XML

Introduction to SVG

This chapter is from the book

This chapter is from the book

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.

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


The code behind the SVG graphic is:

Example 1–2 triangle.svg

1.  <?xml version="1.0" standalone="no"?>
2.  <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"
3.  "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
4.  <svg width="500" height="500">
5.  <path d="M114.286 260 L320 222.857" transform="translate(0 0)"
6.  style="fill:none;stroke:rgb(171,17,17);stroke-width:5"/>
7.  <polygon points="211.429,148.571 208.571,400 325.714,97.1429"
8.  style="fill:rgb(0,0,255);stroke:rgb(0,0,0);stroke-width:1"/>
9.  </svg>
  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 document "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 <svg> element—which consists of the opening <svg> tag and the closing </svg> tag—and includes everything in the document. This is the root element. Width and height are attributes of the <svg> 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 <path> element here has two attributes: d and transform. The d attribute refers to path data, and the values of d are what appear after the equal (=) sign. The numbers you see are x and y coordinates defining the 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. Therefore, 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 transform 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 <path> element. The style attribute can be used to describe a lot of the presentational 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 control 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 <polygon> 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 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 <path> or <polyline>.

    Figure xxxFIGURE 1–9 The image on the left is drawn using the <polyline> element, with three points specified. The image on the right is drawn using the <polygon> element with three points specified. The <polygon> 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 outlined 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 </svg> 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.

Changing Values and Code

It is helpful when learning SVG (as with any programming language!) to play around with the code. So open up your text editor and type in the code for the above drawing:

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"
"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg width="500" height="500">
<path d="M114.286 260 L320 222.857" transform="translate(0 0)"
style="fill:none;stroke:rgb(171,17,17);stroke-width:5"/>
<polygon points="211.429,148.571 208.571,400 325.714,97.1429"
style="fill:rgb(0,0,255);stroke:rgb(0,0,0);stroke-width:1"/>
</svg>

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, triangleTest.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 <path d="M120 100 L400 300". Save the file and view it again. See how the red line has changed?

1.3

Now take a look at the style attribute for our path element. Change the stroke value of the path element (line 6 of code) to style="fill:none; stroke:rgb(17,171,17). Again, save the file and take a look in a browser.

1.4

Now, let's set the path's stroke-width value to 20. Save the file, and take a look.


You should see something similar to the screenshot in Figure 1–10.

Figure xxxFIGURE 1–10 Original triangle.svg file, modified by changing values for the <path> element.


Try altering the code for the polygon element by changing coordinates or by changing style attribute values, such as fill color and stroke color. Remember to save your code and view it in a browser window to see whether the effect you get is the one you intended. You can learn a lot about how basic SVG operates this way!

In this chapter, you've learned to:

  • Download the SVG viewer

  • View an SVG document

  • Recognize an XML file

  • Create both a well-formed and a valid XML file using a text editor

  • Create and save a simple SVG file using a text editor

  • Edit your SVG file and view it in a browser window

  • Change some SVG attribute values and view the results

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020