Home > Articles

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

This chapter is from the book

Gradients in SVG

As well as allowing a greater choice of solid colors, SVG provides elements to allow us to create color gradients. A gradient is a change in color value along a line. For example, a rectangle could be blue at one side and gradually change to pale gray on the other side. In SVG terminology, that is a linear gradient.

In SVG, gradients may be applied to either the stroke or fill of an SVG shape, or both if you prefer. SVG provides two elements, the linearGradient element and the radialGradient element, that, respectively describe linear and radial gradients.

Linear Gradients

A gradient is typically defined using the relevant SVG gradient element nested within a defs element, where all definitions that are to be used elsewhere in an SVG document are located. The relevant element in the definition section is then referenced using a "bare names" form of XPointer as the value of the relevant property of the graphic shape. For example, to define and use a simple linear gradient for a line, we could use code like that shown in Listing 3.16.

Listing 3.16 SimpleLinearGradient.svg—An SVG Linear Gradient

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg width="" height="">
<defs>
<linearGradient id="FirstGradient" >
 <stop offset="0%" style="stop-color:#FF00FF"/>
 <stop offset="100%" style="stop-color:#FFFF00"/>
</linearGradient>
</defs>
<line x1="50" y1="70" x2="250" y2="70"
 style="stroke:url(#FirstGradient); stroke-width:6"/>
</svg>

The visual appearance produced is a line that is magenta in color at the left, gradually changing to yellow at the right end of the line. To see the gradient best, you need to run the code onscreen, but Figure 3.12 may give you some indication of the visual appearance.

Figure 3.12 A horizontal SVG linear gradient.

Notice that the linear gradient is defined in a linearGradient element nested within the defs element of the SVG document:

<defs>
<linearGradient id="FirstGradient" >
 <stop offset="0%" style="stop-color:#FF00FF"/>
 <stop offset="100%" style="stop-color:#FFFF00"/>
</linearGradient>
</defs>

This code snippet defines only a horizontal linear gradient from magenta on the left to yellow on the right. If it is not referenced elsewhere in the SVG document by an SVG element that is to be rendered, the presence of the gradient within the definitions of the document has no effect on the visual appearance produced by the SVG rendering engine. Thus, the code

<line x1="50" y1="70" x2="250" y2="70"
 style="stroke:url(#FirstGradient); stroke-width:6"/>

which references the gradient, is essential to produce a visual effect from the gradient onscreen.

Linear gradients in SVG may be horizontal, vertical, or may be applied diagonally. The default behavior is to produce a horizontal gradient. A linear gradient may have two stop colors, as shown in the earlier example, or may have several, thus producing a number of color transitions within a single graphic.

Let's look at a number of the options for using a linear gradient in SVG. First, let's look at how to apply simple horizontal gradients to the stroke and/or fill of SVG shapes.

Listing 3.17 illustrates the use of three gradients to control the appearance of a linear gradient in the stroke of three SVG line elements.

Listing 3.17 StrokeGradients.svg—Linear Gradients in line Elements

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg width="400" height="500">
<defs>
<linearGradient id="Gradient1" >
 <stop offset="0%" style="stop-color:#FF0000"/>
 <stop offset="100%" style="stop-color:#00FF00"/>
</linearGradient>
<linearGradient id="Gradient2" >
 <stop offset="0%" style="stop-color:#0000FF"/>
 <stop offset="100%" style="stop-color:#FFFFFF"/>
</linearGradient>
<linearGradient id="Gradient3" >
 <stop offset="0%" style="stop-color:#FFFF00"/>
 <stop offset="100%" style="stop-color:#0000FF"/>
</linearGradient>
</defs>
<line x1="20" y1="20" x2="220" y2="20"
 style="stroke:url(#Gradient1); stroke-width:4"/>
<line x1="20" y1="40" x2="220" y2="40"
 style="stroke:url(#Gradient2); stroke-width:4"/>
<line x1="20" y1="60" x2="220" y2="60"
 style="stroke:url(#Gradient3); stroke-width:4"/>
</svg>

As you can see in Figure 3.13, which is zoomed and panned, we again have three lines. If you download and run the code, you will see that each of the three lines has a simple linear gradient, but the color values for each gradient are distinct. The first line has a gradient from red at the left to green at the right. The second line has a gradient from blue at the left to white at the right, and the third line has a linear gradient from yellow at the left to blue at the right.

Figure 3.13 Three linear gradients on line elements.

We can apply similar gradients to the fill of shapes. For example, we can create simple linear gradients in the fill of SVG rect elements, as well as in the fill of other graphic shapes. Listing 3.18 shows how simple linear gradients can be applied to rectangular shapes, such as those you might use in a bar chart.

Listing 3.18 FillGradients.svg—Applying a Linear Gradient to the Fill of a Shape

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg width="400" height="500">
<defs>
<linearGradient id="Gradient1" >
 <stop offset="0%" style="stop-color:#FF0000"/>
 <stop offset="100%" style="stop-color:#00FF00"/>
</linearGradient>
<linearGradient id="Gradient2" >
 <stop offset="0%" style="stop-color:#0000FF"/>
 <stop offset="100%" style="stop-color:#FFFFFF"/>
</linearGradient>
<linearGradient id="Gradient3" >
 <stop offset="0%" style="stop-color:#FFFF00"/>
 <stop offset="100%" style="stop-color:#0000FF"/>
</linearGradient>
</defs>
<rect x="40" y="25" width="300" height="75"
 style="stroke:red; fill:url(#Gradient1)"/>
<rect x="40" y="175" width="300" height="75"
 style="stroke:red; fill:url(#Gradient2)"/>
<rect x="40" y="325" width="300" height="75"
 style="stroke:red; fill:url(#Gradient3)"/>
</svg>

Each rectangle has a red stroke. The fill of each rectangle is defined in the linearGradient elements, which are then referenced by the fill property of the style attribute of each rect element. For example, we apply the previously defined linear gradient to the fill of the top rectangle using the following code:

style="stroke:red; fill:url(#Gradient1)"

Up to this point, we have relied on the default behavior of the SVG rendering engine to produce a horizontal linear gradient. We can make that explicit by adding x1, y1, x2, and y2 attributes to the linearGradient element nested within the defs element. Listing 3.19 shows how this is done.

Listing 3.19 ExplicitHorizGradients.svg—Creating Horizontal Gradients Explicitly

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg width="400" height="500">
<defs>
<linearGradient x1="0%" y1="0%" x2="100%" y2="0%" id="Gradient1" >
 <stop offset="0%" style="stop-color:#FF0000"/>
 <stop offset="100%" style="stop-color:#00FF00"/>
</linearGradient>
<linearGradient x1="0%" y1="0%" x2="100%" y2="0%" id="Gradient2" >
 <stop offset="0%" style="stop-color:#0000FF"/>
 <stop offset="100%" style="stop-color:#FFFFFF"/>
</linearGradient>
<linearGradient x1="0%" y1="0%" x2="100%" y2="0%" id="Gradient3" >
 <stop offset="0%" style="stop-color:#FFFF00"/>
 <stop offset="100%" style="stop-color:#0000FF"/>
</linearGradient>
</defs>
<rect x="40" y="25" width="300" height="75"
 style="stroke:red; fill:url(#Gradient1)"/>
<rect x="40" y="175" width="300" height="75"
 style="stroke:red; fill:url(#Gradient2)"/>
<rect x="40" y="325" width="300" height="75"
 style="stroke:red; fill:url(#Gradient3)"/>
</svg>

Notice that the values of the x1 and x2 attributes of each linearGradient element differ, indicating that the gradient changes on a horizontal axis, that is, as we move from the x1 to x2 positions. The visual appearance is as before.

We can produce a vertical gradient in each rectangle by making the values of the x1 and x2 attributes the same, indicating no change in the gradient along a horizontal axis, and by introducing a difference in the values of the y1 and y2 attributes, indicating that there is a change in the appearance of the gradient along the y axis; that is, it is a vertical gradient. Listing 3.20 shows how to do this.

Listing 3.20 ExplicitVertGradients.svg—Creating Vertical Gradients in SVG

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg width="400" height="500">
<defs>
<linearGradient x1="0%" y1="0%" x2="0%" y2="100%" id="Gradient1" >
 <stop offset="0%" style="stop-color:#FF0000"/>
 <stop offset="100%" style="stop-color:#00FF00"/>
</linearGradient>
<linearGradient x1="0%" y1="0%" x2="0%" y2="100%" id="Gradient2" >
 <stop offset="0%" style="stop-color:#0000FF"/>
 <stop offset="100%" style="stop-color:#FFFFFF"/>
</linearGradient>
<linearGradient x1="0%" y1="0%" x2="0%" y2="100%" id="Gradient3" >
 <stop offset="0%" style="stop-color:#FFFF00"/>
 <stop offset="100%" style="stop-color:#0000FF"/>
</linearGradient>
</defs>
<rect x="40" y="25" width="300" height="75"
 style="stroke:red; fill:url(#Gradient1)"/>
<rect x="40" y="175" width="300" height="75"
 style="stroke:red; fill:url(#Gradient2)"/>
<rect x="40" y="325" width="300" height="75"
 style="stroke:red; fill:url(#Gradient3)"/>
</svg>

You have seen how we can explicitly produce a horizontal gradient by specifying differing values for the x1 and x2 attributes of the linearGradient element and how we can produce a vertical gradient by using different values for the y1 and y2 attributes. To produce a diagonal gradient, we simply ensure that both attribute pairs—the x1 and x2 and y1 and y2 attributes—have different values. Listing 3.21 shows this in practice.

Listing 3.21 SimpleDiagonalGradient.svg—A Diagonal Linear Gradient

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg width="400" height="500">
<defs>
<linearGradient x1="0%" y1="0%" x2="100%" y2="100%" id="Gradient2" >
 <stop offset="0%" style="stop-color:#0000FF"/>
 <stop offset="100%" style="stop-color:#FF0000"/>
</linearGradient>
</defs>
<rect x="40" y="25" width="300" height="300"
 style="stroke:red; fill:url(#Gradient2)"/>
</svg>

Onscreen you will see a square that is blue in the top-left corner, shading through various shades of purple down and to the right, finishing with red in the bottom-right corner.

As well as specifying a stop-color property for each stop element, you may also specify a stop-opacity property, thus allowing partially transparent gradients to be created.

Radial Gradients

Producing a radial gradient rather than a linear gradient requires a syntax that is very similar to that for a linear gradient. The radialGradient element is nested within a defs element and has an id attribute that is then referenced as the fill or stroke property of an SVG graphic shape. The syntax of the radialGradient element differs slightly, as you can see in Listing 3.22.

Listing 3.22 SimpleRadialGradient.svg—Creating a Simple Radial Gradient in SVG

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg width="400" height="400">
<defs>
<radialGradient id="FirstRadialGradient" gradientUnits="userSpaceOnUse"
 cx="200" cy="200" r="150" fx="200" fy="200">
 <stop offset="0%" style="stop-color:#FF00FF"/>
 <stop offset="25%" style="stop-color:#00FF00"/>
 <stop offset="50%" style="stop-color:#FFFF00"/>
 <stop offset="75%" style="stop-color:#0000FF"/>
 <stop offset="100%" style="stop-color:#FFFF00"/>
</radialGradient>
</defs>
<rect x="0" y="0" width="400" height="400"
 style="fill:url(#FirstRadialGradient);"/>
</svg>

The cx and cy attributes on the radialGradient element define the center position of the gradient. The r attribute defines the radius over which the radius applies. The fx and fy attributes define the focal point for the gradient.

The visual appearance produced onscreen is pretty strident but does give you some indication of the types of visual effects that can be produced using radial gradients. Figure 3.14 shows the onscreen appearance when Listing 3.22 is run.

Figure 3.14 A vibrant radial gradient.

Radial gradients on a much smaller scale can, when combined with declarative animation elements, be used to create visually unmissable markers for important content. Be careful, however, not to overdo the effect, or you may simply irritate the users.

  • + 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