Home > Articles

SVG's Shape Toolbox

This chapter is from the book

This chapter is from the book

Paths

The path element is similar to the polyline and polygon elements in the sense that it is used to draw continuous lines. Using the basic shapes you've read about thus far is really not much different than describing the objects in the path format, other than that their required information set is far simpler. In other words, drawing with basic shape elements is much easier than defining every simple shape as a series of coordinates and directional notations by using the path element. However, the path element allows you to draw anything the basic shapes allow, plus much more.

A path need not be comprised of straight lines, as polyline and polygon are forced to be. As curves are supported with the path element, more information than coordinates is required, making path considerably more complex than previous shapes.

If you are familiar with Bézier curves and illustration programs then you will have a leg up in this area, as paths operate under similar concepts in those applications. For every curve rendered, four coordinates are required: two coordinates for the beginning and end of the line and two coordinates for defining the arc of the curve. To illustrate this concept, take a look at Figure 5.9.

Figure 5.9 Four coordinates are required to define any curve.

In Figure 5.9, the two points of the line are represented as 'P1' and 'P2,' whereas the two coordinates defining the degree of the arc are 'B1' and 'B2.' In illustration programs, the lines you see above (extending from the line points to the arc points) are dubbed "arc handles." They do not visibly appear in the final illustration, but rather help designers visualize how their curves are being created. To change the degree and direction of the arc between these two points, you simply need to change the location of the 'B1' and 'B2' points, as shown in Figure 5.10.

Figure 5.10 To adjust the arc of a curve, simply modify the "arc handle" coordinates.

As you can see, the complexity of information required to define a line has significantly increased. Thankfully, the news center illustration you will be creating throughout this book does not require extensive path illustrations. To illustrate the use of the path element, you will create the raindrops for the thunderstorm illustration in the weather graphic. The raindrop serves as a good example, as it contains both straight and curved lines.

The path element requires significantly different notation than our other elements. Rather than a points attribute, as you saw in the polyline and polygon elements, path uses the d attribute to define the list of coordinates and directions that describe the displayed line. As you're describing arc and curve data, you'll need to include additional commands with your coordinates.

The syntax for the d attribute may seem a bit complex at first glance. The values associated with the d attribute are a series of coordinates and "path commands." These values always start with M (which signifies the starting of a path) and are followed by an x,y coordinate (which defines the starting point of the path). What follows next depends on what kind of path you are trying to draw (whether straight or curved) and how complex it is. Although there are several path commands available to accomplish these tasks, the most common commands are presented in Table 5.1.

Table 5.1 Common path Commands

Command

Meaning

Description

M

Moveto

Used to start a path. For example, "<path d="M x1,y1..."/>

L

Lineto

The L command draws a straight line from the previous coordinates to the coordinates following the command. For example, "<path d="M x1,y1 L x2,y2 "/>

C

Curveto

Used to draw a curve. Followed by three coordinates, the C command requires a total of four coordinates to define a curve. It takes the coordinate previous to its location ("P1" in Figure 5.9) as its starting point, establishes the first following coordinate as the first arc handle ("B1"), the second coordinate as the second arc handle ("B2"), and the third coordinate as the end point of the curve. For example, "<path d="M x1,y1 C x2,y2 x3,y3 x4,y4 "/>

Z

Closepath

The Z command closes off a path, similar to the way the polygon element closed our lightning bolt illustration. For example, "<path d="M x1,y1 L x2,y2 x3,y3 Z"/>


path commands use capitalized letters to refer to absolute coordinates, meaning that x1,y1 and x2,y2 refer to specific points on our SVG document's grid. However, if you use lower case letters instead, the path element will think of the coordinates following the lowercase command as relative. In other words, x2,y2's position would not be plotted in relation to the document's 0,0 position, but rather from the position of x1,y1.

To demonstrate the difference between absolute and relative coordinates in path commands, you should observe the difference between the examples shown in Figure 5.11. Both examples draw the same line, but you will notice that the coordinates listed in the example to the right (except for the start point of the path) don't match the document's coordinates. That's because the coordinates are relative to the first coordinates. The coordinates given in the left example are absolute, meaning that they refer to specific coordinates within the SVG document's coordinate system. The first arc handle's coordinates are listed as 12,0, meaning that the arc handle's position is 12 pixels to the right and 0 pixels down from the previous coordinates' location.

Figure 5.11 Compare the manner in which absolute (left) and relative (right) path commands draw the same line.

Absolute and relative coordinate systems each have their own advantages. Absolute coordinates are oftentimes easier to plot initially but require lots of mental math to move the object around. You either need to recalculate every coordinate in the path or use a transformation on the entire path (covered in Hour 14, "Transforms"). Relative coordinates, on the other hand, are easier to move around the page. You need only edit the first coordinate in the path, and the subsequent coordinates follow.

To further explore the path element and its complexities, creating the raindrop from the news center's thunderstorm weather graphic will provide a solid example. Before you begin coding, however, you will need to plan the coordinates of the drop. Similar to the way the lightning bolt was plotted earlier in this hour, you will need to draw the raindrop out on your graph paper (Figure 5.12).

Figure 5.12 The raindrop to be drawn in SVG, overlaying a grid in order to demonstrate the coordinates required to draw such a path.

You'll notice that the top of the raindrop does not have "arc handles" that define the curve's arc. They have been intentionally left off to create the sharp point; thus, the handles share the same coordinates as the point itself (effectively eliminating any curvature).

To create the raindrop for the thunderstorm illustration, you will need to take the coordinates displayed in Figure 5.11 and use them in conjunction with the path commands from Table 5.1, mentioned earlier in the hour. By combining these two chunks of information, you can create the illustration in SVG (shown in Figure 5.13), similar to the code shown in Listing 5.10.

Listing 5.10 Using Absolute Points in the path Element to Create a Raindrop Illustration

01: <?xml version="1.0" standalone="no"?>
02: <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"
03:  "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
04:
05: <svg width="500" height="300">
06:
07:   <path d="M16,0
08:     C 16,0 0,24 0,33
09:     C 0,42 7,49 16,49
10:     C 25,49 32,42 32,33
11:     C 32,24 16,0 16,0" />
12:
13: </svg>

Figure 5.13 Using the coordinates determined in Figure 5.12, you can draw this raindrop illustration quickly in SVG using the path element.

If you look at line 7 in this code, you will see that the path begins at the coordinates 16,0. (Thinking back to the diagram in Figure 5.10, these coordinates are similar to "P1.") As line 8 begins with a capital C, you know two things: 1) you will be defining a curve and 2) the coordinate system is absolute.

The last coordinates on line 8 describe the next point on the path, and the cycle begins again, with the C command designating the next two coordinate pairs as arc handle points and the remaining coordinate pair as the next path point.

If you wanted to move this raindrop illustration out of the corner of the document, you'd have to recalculate every coordinate to accommodate for the shifted x and y positions. As you can imagine, there are probably things you'd rather be doing in the middle of a coding project than a series of calculations. To accommodate developers who want the ability to easily move their paths around their documents, the relative path commands were defined.

As shown back in Figure 5.11, relative paths look the same as absolute paths; only their coordinates and notation are different. To assist in creating a relative path example using the same raindrop, you'll need to plot the points in terms of their relationship to other points. Compare Figure 5.12, which shows the absolute system's coordinates, with Figure 5.14, which shows the relative system's coordinates.

Figure 5.14 The same raindrop as Figure 5.12 but plotted with relative coordinates. Notice how only the topmost coordinate pair is in accordance with the document's coordinates. The remaining coordinate pairs are relative to their previous path command.

Only the topmost coordinates adhere to the document's coordinate system. Moving in a counter-clockwise direction, the next three coordinate pairs (0,0 -16,24 -16,33) are relative to the topmost. The next three coordinate pairs (0,9 7,15 16,15) are relative to the point immediately previous to it (-16,33). Such coordinates produce the beginning code for the path element:

<path d="M 16,0
  c 0,0 –16,24 –16,33
  c 0,9 7,15 16,15
  ../>

This structure mimics the absolute path command's syntax; the first coordinate pair (immediately after the start command: M) represents a point on the path, the two pairs immediately following the path command (c, in this case) represent arc handles, and the third and final pair represents the next point on the path. The cycle continues again, this time with the coordinates relating to the previous coordinate. Translating all the plotted coordinates to the appropriate path command translates into the code shown in Listing 5.11.

Listing 5.11 Using Relative Points in the path Element to Create a Raindrop Illustration

01: <?xml version="1.0" standalone="no"?>
02: <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"
03: "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
04:
05: <svg width="500" height="300">
06:
07:   <path d="M16,0
08:     c 0,0 –16,24 –16,33
09:     c 0,9 7,15 16,15
10:     c 9,0 16,–7 16,–15
11:     c 0,–9 –16,–33 –16,–33"/>
12:
13: </svg>

The benefit of relative path values is the ease of moving your path around the document. For instance, changing the initial start point of the path (16,0) to a more central point (250,140) simply moves the entire artwork (see Figure 5.15). If you apply the same change to the code in Listing 5.10, the top point of the raindrop will be stretched to the document's center point, but the remainder of the image will retain its original place.

Figure 5.15 Using the relative coordinates determined in Figure 5.14, you can draw a raindrop that can easily be repositioned.

On a small scale, such as that of a raindrop, drawing with paths doesn't seem so tough. As your path illustration becomes more complex, however, mastering path commands becomes essential.

NOTE

Programs such as Adobe Illustrator and Jasc WebDraw allow for their artwork to be exported as SVG files. Thus, by using one of these tools (or any of the others that are available), you can significantly reduce the amount of time required to draw complex paths in the code by hand.

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