Home > Articles

SVG's Shape Toolbox

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Basic Shapes

Drawing shapes in SVG can be quite simple. Whereas most designers use their drawing program's shape tools to eyeball the dimensions and placement of the shapes they draw, SVG demands precision from the start. You will never need to guess whether some piece of your artwork is aligned with another, as the mathematical coordinates you use to define every piece of artwork will answer such a question. Although entering exact values for every element may seem a bit demanding of the designer at first, you will quickly come to appreciate the opportunities this precision affords.

In some ways, it is more fitting to think of drawing in SVG with words than with a paintbrush. To help ease this "verbal drawing," the authors of the specification created a series of SVG elements that literally interpreted their own described shapes. By using the rect, circle, ellipse, and line elements, you will get exactly the described object.

Two other available drawing elements are the polyline and polygon elements. Whereas the line element defines only a straight line with two points, the polyline element defines a sequence of straight lines. The polygon element is much the same, except that it is used for defining a multi-lined element that is closed.

Rectangles

The rectangle is likely the most common object you will draw, and drawing such a box is made possible using the rect element. The rect element has four easy-to-understand attributes that define its position and size:

x
y
width
height

The x and y attributes define the coordinates of the starting corner of the rectangle, whereas width describes the horizontal measurement (moving right of the x coordinate if a positive value) and height describes the vertical measurement (moving south of the y coordinate if a positive value).

Using the news center graphic referred to at the end of Hour 1, you can begin using the rect element to build this graphic. To illustrate how the rect element operates, begin by creating the initial outline of the news center, as shown in Listing 5.1. Using the 500-pixel width and 300-pixel height document dimensions shown in previous figures, start the rect element 10 pixels from the document's edge to provide a comfortable margin around the piece.

Listing 5.1 Drawing the Outline of the Content Area for the News Center Graphic

 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:   <rect id="Outline" x="10" y="10" width="480" height="280"/>
 08:
 09: </svg>

You'll notice several things in the code you just created:

  1. In line 5, you created a 500-pixel wide by 300-pixel tall SVG document.

  2. In line 7, you've created a 480-pixel wide by 280-pixel tall rectangle that has an even 10 pixels between the rectangle's edge and the document's edge.

  3. Also in line 7, you've used an id attribute (which you learned about in Hour 3) within the rect element to name the particular use of this rectangle. While naming elements may seem meaningless in such a small example, it's a good habit to get into.

NOTE

As mentioned last chapter, any unit that is not specified is actually a "user space value." For the simplicity of the explanations in this book, the assumption is that you will be viewing these examples within an Internet browser on your computer, and thus the term "pixels" is used. If you do not, then the values may be interpreted in a unit of measurement standard to that device.

When you open the above document in your browser, you will notice that a giant black 480 x 280 rectangle appears, as shown in Figure 5.1. Without any style definitions applied, all elements will appear with a black fill and without a stroke (or outline). As you will be covering style in the next hour, you need not worry about the large rectangle's current appearance.

Figure 5.1 A simple rectangle that will serve as the outline of the book's news center example.

Now that you've taken the first step in creating the news center, you'll proceed in Listing 5.2 to create the remaining major rectangles used in the file. Notice that each item should be labeled with its own unique id attribute. As none of the rectangles have any specified style information, they will all appear as black boxes; as you created the document's outline previously, none of the rectangles you create next will be discernible over the top of the large "Outline" rectangle.

Listing 5.2 Adding Major Rectangles to the News Center Graphic Code

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:   <rect id="Background" x="0" y="0" width="500" height="300"/>
08:   
09:   <rect id="BkgdSun" x="10" y="45" width="200" height="245"/>
10:   
11:   <rect id="Outline" x="10" y="10" width="480" height="280"/>
12:
13:   <rect id="BarTitle" x="10" y="10" width="480" height="35"/>
14:   
15:   <rect id="BarStatistics" x="10" y="245" width="200" height="45"/>
16:   
17: </svg>

In this example, you have created a series of black rectangles, one on top of the other, but you have no way to discern which is which. Before moving to circles, there is a convenient trick that can help you hide objects from view.

As you learned in Hour 2, "SVG's Foundation," any content, whether plain English or SVG code, enclosed with comment tags will not be interpreted, and thus not displayed. (Remember, though, that a comment may not reside within another comment or within a tag.) Thus, to make sure the rectangles you just created appear properly, you can "hide" all but one by placing them inside the comment tags. Before hiding any objects, you should begin by creating a sample document. For example, the code in Listing 5.3 shows a valid use of the comment in lines 17, 18, and 19.

Listing 5.3 Proper Use of the Comment

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:   <rect id="Background" x="0" y="0" width="500" height="300"/>
08:   
09:   <rect id="BkgdSun" x="10" y="45" width="200" height="245"/>
10:   
11:   <rect id="Outline" x="10" y="10" width="480" height="280"/>
12:
13:   <rect id="BarTitle" x="10" y="10" width="480" height="35"/>  
14:   
15:   <rect id="BarStatistics" x="10" y="245" width="200" height="45"/>
16:   
17:   <!--
18:     This is a comment field.
19:   -->
20: </svg>

As the code in Listing 5.2 appears in your browser, you'll notice that you still can't see any of the new rectangles, as they simply appear as black rectangles on top of one large black rectangle. To solve this issue, you can use the comment tags to surround each of the rectangle elements that you want to prevent from displaying. By containing several of the rect elements within the comment field, you will be able to see the one remaining rectangle's placement when viewed with an SVG viewer.

Listing 5.4 shows such a use of the comment tags. On line 7, the comment bracket opens and contains all but one of the rectangles by the time it closes on line 17. Line 19's rectangle is the only one that will appear as a viewer parses the SVG document (shown in Figure 5.2), as it remains outside of the comment's tags.

Listing 5.4 Using the Comment to Prevent Elements from Displaying

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:   <!--
08:
09:     <rect id="Background" x="0" y="0" width="500" height="300"/>
10:
11:     <rect id="BkgdSun" x="10" y="45" width="200" height="245"/>
12:
13:     <rect id="Outline" x="10" y="10" width="480" height="280"/>
14:
15:     <rect id="BarTitle" x="10" y="10" width="480" height="35"/>
16:
17:   -->
18:
19:   <rect id="BarStatistics" x="10" y="245" width="200" height="45"/>
20:   
21: </svg>

Figure 5.2 By enclosing all the rect elements except one within a comment, only the rectangle in the lower left corner with the id value of "BarStatistics" is visible.

In this way, comments serve two purposes for developers: 1) to insert notes in plain English to describe neighboring content's purpose or 2) to disable code, preventing the comments' content from rendering and functioning (as in the case of an animation or interaction), thus allowing for selective development and testing.

Circles

Arguably as commonly used as rectangles, circles are incredibly easy to create. The circle element has three frequent attributes, unlike rectangle's four. To define a circle, you need to know only the center point coordinates and the radius. The attribute names are as follows:

cx

center point coordinate

cy

center point coordinate

r

radius


To keep your examples in terms of the news center graphic you'll be creating throughout this book, begin using the circle element to draw the sun in the weather illustration. In line 7 of Listing 5.5, you'll see the circle element with its three attributes. The cx and cy attributes are positioning the circle's center point in accordance with the news center graphic, whereas the r attribute sizes the circle's radius according to the sun's width. Figure 5.3 shows the result of this code.

Listing 5.5 Creating a Circle

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:   <circle id="Sun" cx="105" cy="160" r="56"/>
08:
09: </svg>

Figure 5.3 A simple circle serves as the foundation for the sun illustration in the news center's weather graphic.

With only three important attributes to remember, the circle element provides a quick and easy method of drawing circular objects.

Ellipses

Similar to the circle element, the ellipse element creates an oval, whether circular or oblong in nature. The syntax for the ellipse element has four attributes:

cx

center point coordinate

cy

center point coordinate

rx

horizontal radius

ry

vertical radius


To illustrate the ellipse element, take the same coordinates you used to create the center point of the circle in the last exercise. As the ellipse has two radiuses (one horizontal, one vertical), you'll need to provide two separate values. In line 9 of Listing 5.6, the value for the horizontal radius is made greater than the value for the vertical radius to show the difference in appearance between the ellipse and the circle. Figure 5.4 shows the wide ellipse in the circle's former location.

Listing 5.6 Creating an Ellipse

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: <ellipse cx="105" cy="160" rx="56" ry="35"/>
08:
09: </svg>

Figure 5.4 An ellipse uses syntax similar to the circle, except that it allows for different radiuses for the height and width.

The ellipse element can easily make circles as well. By making the rx and ry values the same, the resulting ellipse is a perfect circle.

Lines

The line element is also a very simple shape to create. There are only four attributes for this element: x1, x2, y1, and y2. x1 and y1 represent the initial x,y coordinates of the line, whereas x2 and y2 represent the end coordinates. Listing 5.7 shows the simplicity of the line element and is displayed in Figure 5.5. You'll need to include a style property in the line element, as shown in line 7, otherwise the line will render invisible in some viewers. (Don't worry; you'll learn all about how to apply style in the next hour.)

Listing 5.7 Creating a Line

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: <line x1="105" y1="160" x2="410" y2="100" style="stroke:black;"/>
08:
09: </svg>

Figure 5.5 A line is quickly created with two sets of coordinates: one for the start point and one for the end point.

Drawing a line is a simple process. Know your four points (2 for the start point and 2 for the end point) and you've got all you need to define this element.

Polylines and Polygons

polyline and polygon elements are very similar; their differences lie only in whether the produced shape is closed. To draw using these elements, you'll need a different set of notations than that used for the previous shapes. Whereas with the rect element, you defined beginning 'x' and 'y' coordinates followed by width and height attributes, you will now use only (x,y) coordinates to define the points of a polyline or polygon.

The syntax for both polyline and polygon elements is the same. To describe a polyline or a polygon, you must add a points attribute. The value for the points attribute is a list of coordinate pairs (two coordinates separated by a comma) separated by whitespace (such as a space or a line break). Lines are drawn sequentially, connecting the coordinates in the order they are listed, starting with the first point and continuing to the last. In the case of the polygon, a line will connect the last point listed and the first, effectively "closing" the artwork.

To help distinguish the subtle differences between the polyline and polygon elements, you can create a lightning bolt for the news center's weather example by using each element. The bolt is commonly rendered with only eleven points to define its jagged edges. To understand the coordinates you'll be using (whether in the bolt illustration or otherwise), it often helps to draw the illustration on graph paper. By using this ruled and numbered grid, plotting precise coordinates becomes quite simple. (To assist you, a reproducible grid has been included in Hour 24, "References.") To represent the bolt, draw out Figure 5.6:

Figure 5.6 Define your artwork on a grid to determine the coordinates it will require. In this case, a lightning bolt can be simplified to eleven necessary coordinates.

Using these eleven coordinates, you would then create the document, as shown in Listing 5.8. Note that the points for the bolt are listed in the value of the points attribute. Each (x,y) coordinate is separated by whitespace. To see whether the object is closed or not, you will need to add two brief style properties to your artwork (shown on line 8). The lightning bolt is shown in Figure 5.7.

Listing 5.8 Figure 5.7's Lighting Bolt Drawn with the polyline Element

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:
08:   <polyline style="stroke:black; fill:yellow;"
09:     points="248,115
10:       239,140 243,140
11:       237,163 241,163
12:       235,187
13:       253,159 249,159
14:       261,136 256,136
15:       267,115" />
16: </svg>

Figure 5.7 A lightning bolt is drawn using the polyline element.

The result is a beautiful, yellow lightning bolt with no top. Technically, you could create a twelfth point to close the bolt; however, the polygon element will do the same trick with the existing coordinates. By replacing the polyline element with the polygon element, as shown in Listing 5.9 (line 8), the bolt will have an outline around its entire perimeter (Figure 5.8).

Listing 5.9 Figure 5.8's Lighting Bolt Drawn with the polygon Element

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:
08:   <polygon style="stroke:black; fill:yellow;"
09:     points="248,115
10:       239,140 243,140
11:       237,163 241,163
12:       235,187
13:       253,159 249,159
14:       261,136 256,136
15:       267,115" />
16: </svg>

Figure 5.8 A lightning bolt gains its top, defining line using the polygon element.

By simply using the polygon element, the same coordinates result in a solid, closed shape. Although saving one coordinate pair's worth of information may not seem to be worth the hassle, remember that the simpler your files are constructed, the simpler they are to manage. The importance of this will manifest itself later in this book, as we compound several items together.

  • + Share This
  • 🔖 Save To Your Account

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