Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your profile (name, country/region, and company) is displayed to the public and will accompany any content you post. You may update your IBM account at any time.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

Create client-side diagrammatic interaction in Web applications with SVG

Set up an example of Web-based SVG co-operation

Cameron Laird (claird@phaseit.net), Vice President, Phaseit, Inc.
Photo of Cameron Laird
For long-time developer Cameron Laird, "graphics" has, on different occasions, meant everything from images of brains scans and aircraft cockpit displays to pipeline control boards and commodity market charts. He's an enthusiastic Invited Expert to the SVG Interest Group precisely because SVG promises to relieve so many problems common to these diverse domains. Cameron also is a prolific author of articles for developerWorks and other professional publications, as well as the Smart Development blog. Cameron consults as vice-president of Phaseit, Inc., which he co-founded, and can be reached as claird@phaseit.net.

Summary:  The maturity of SVG allows for a little-known style of use and development of currently undocumented visual elements. In a time when data-as-a-service is blossoming, it makes a lot of sense to script SVG instances from an enclosing Web application. A specific example of a dynamic choropleth illustrates how easy this technique can be.

Date:  06 Apr 2010
Level:  Intermediate PDF:  A4 and Letter (505KB | 18 pages)Get Adobe® Reader®
Also available in:   Chinese  Korean  Japanese

Activity:  31827 views
Comments:  

Introduction

Frequently used acronyms

  • CSS: Cascading stylesheet
  • DAAS: Data as a service
  • DOM: Document Object Model
  • GIF: Graphics Interchange Format
  • GUI: Graphical User Interface
  • HTML: Hypertext Markup Language
  • JPEG: Joint Photographic Expert Group
  • MVC: Model View Controller
  • PNG: Portable Network Graphic
  • SVG: Scalable Vector Graphics
  • SOA: Service-oriented architecture
  • TIFF: Tag Image File Format
  • WSDL: Web Services Description Language
  • XHTML: Extensible Hypertext Markup Language
  • XML: Extensible Markup Language

This article presents a single concrete Web page which will interest both Web developers and their managers. While the coding is simple enough to be thoroughly understood, it models a GUI effect that goes beyond traditional form-based Web application. The effect:

  • Depends only on public standards
  • Performs at least as well as proprietary alternatives
  • Opens up new models of teamwork and collaboration
  • Represents an implementation technique that has apparently never before been documented explicitly

This article has three aims:

  • Demonstrate the operation of a specific standards-compliant Web-based GUI effect for a user perspective
  • Explain the model as an example of deep partnership between Web and SVG technologies from a developer's perspective
  • Illustrate how HTML5 promotes new divisions of labor in development of complex Web applications, as team leads will want to know

This article is written for those who can effectively read the HTML and JavaScript typical of Web pages, but not necessarily write these languages fluently. No prior experience with SVG is necessary. Familiarity with XML is required. While there is no dependence in the presentation on a particular operating system, exposure to a range of browsers is expected.


A working example

To run the examples in this article, use a modern browser other than Microsoft® Internet Explorer®: Safari, Opera, Chrome, Firefox, and QtWeb generally do best. While there are at least a couple of effective ways to run the SVG of this article within Internet Explorer, it's less distracting simply to rely on one of the more standards-compliant browsers for the duration of this article.

It's crucial that you experience for yourself the effect this Web page provides. Look first at the working example at the center of this article from my Web site; the link is in the first entry in Resources. Or, you can download the source files from Download, unzip it, and open the outside_in.html file in your browser. In either case, it should come up in your browser looking something like Figure 1, where all 50 states and U.S. territories are one solid color. A map of the entire country (with inset maps of the Virgin Islands, Guam, and District of Columbia) is shown in a solid color that represents the food stamp participation rate of that state. In this example, the solid color is red when the participation rate is 0.0 percent.


Figure 1. Coloring of states' participation rates when the selected threshold is 0.0
Map of the entire United States, including its territories, all in red

Part of the effect is its dynamic response. In the working example, move the slider pointer at the top of the display a bit to the right (that is, grab it with your mouse pointer, drag it over, then release the first button). You'll see that the number labeled threshold updates, likely from 0.0 to a value such as 6.2. Immediately after, the map recolors itself to match the new threshold. The map coloring means: all states with a foodstamp participation rate below the threshold appear in white, and those whose foodstamp rates are at least twice the threshold are red. States whose foodstamp rate are intermediate—more than the threshold, but less than twice the threshold—show in yellow.


Snapshots

Consider an example: In June of 2009, Nebraska reported 7.8% of its residents used foodstamps. If the threshold is set to any value between 0 and 3.9, as in Figure 2, Nebraska appears red. In this example, a map of the entire country (with inset maps of the Virgin Islands, Guam, and District of Columbia) shows the states of Wyoming and New Jersey as solid yellow in color and all other states and territories as solid red in color.


Figure 2. Coloring of states' participation rates when the selected threshold is 3.1
Map of the entire United States; all states in red, except Wyoming and New Jersey in yellow

When the threshold is 3.9 to 7.8, as in Figure 3, Nebraska shows up yellow. In this example, a map of the entire country (with inset maps of the Virgin Islands, Guam, and District of Columbia) shows Nebraska and most states and territories as solid yellow in color, 17 states as solid red in color, and four states as solid white in color.


Figure 3. Coloring of states' participation rates when the selected threshold is 6.9
Map of the entire United States; Nebraska and most states and territories in yellow, 17 in red, four in white

For any value higher than 7.8, the color of the state changes to white. In Figure 4, the selected threshold is 9.9. In this example, a map of the entire country (with inset maps of the Virgin Islands, Guam, and District of Columbia) shows 17 states and territories as solid white in color and the rest as solid yellow in color.


Figure 4. Coloring of states' participation rates when the selected threshold is 9.9
Map of the entire United States; 17 states and territories are solid white in color and rest are solid yellow in color

As the value in the Threshold field changes in the animation, the color of a state or territory changes based on the food stamp participation rate of that state. (View the animated example.) In the example, the views rotate through the following threshold values and colors.

  • 0.0 threshold value - All states and territories are solid red in color (as in Figure 1).
  • 3.1 threshold value - The states of Wyoming and New Jersey are solid yellow in color and all other states and territories are solid red in color (as in Figure 2).
  • 6.9 threshold value - Most states and territories are solid yellow in color, 17 states and territories are solid red in color, and four states are solid white in color (as in Figure 3).
  • 9.9 threshold value - 17 states and territories are solid white in color and rest are solid yellow in color (as in Figure 4).
  • 20.0 threshold value - All states and territories are solid white in color (as in Figure 5).

Motivation

SVG makes its strongest immediate impression with the complex animations it enables. Those are explained elsewhere, and you can find links to those articles in Resources.

The idea of this article is subtler, and usually easier to grasp if you first watch a knowledgeable presenter illustrate points as he moves in physical space and time. It hinges on information flowing in two directions, both from the diagram to your eye, but also back from your brain through the mouse pointer to the live diagram.

Notice the geographic patterns that appear as you adjust the threshold. This sort of business intelligence often is available only through visualizations. The central interactive concept is powerful in exactly the same way as all the what-if scenarios the first generation of computerized spreadsheets enabled: it affords an irreplaceable dynamic dimension to understanding the underlying subject matter, whether it's the geography of foodstamp participation or the shape of stresses in the vicinity of an earthquake epicenter.

Until recently, though, dynamic graphical interaction was largely the domain of proprietary or desktop applications. As this article shows, SVG now makes a good foundation for advanced standards-based effects with Web applications. SVG and, more generally, the collection of capabilities abbreviated as HTML5, open Web application development to dramatic new frontiers.

The next section documents the implementation behind the food stamp participation display you now understand as a user.

Code explanation

Now review the code that creates the SVG display.

Inventory of materials

The essential architecture of the example involves two sources:

  • outside_in.html defines most of the application.
  • usa_map.svg is a basic map of the United States encoded as SVG, and is referenced from outside_in.html.

Both these are written to be readable by humans; you're welcome to bring up either in your browser and examine the source files.

The current implementation of the demonstration actually segments parts of outside_in.html into multiple JavaScript .js source files. For the present purpose, this is merely a matter of convenience; think of them as part of the .html source, or, more precisely, an aspect of source organization unaffected by the presence of SVG. Partition your .html and .js source files according to your usual software engineering principles.

usa_map.svg, however, stands on its own: Your browser can load it by itself, just as you might view a GIF, JPEG, PNG, TIFF, or other image format in isolation. When your browser first brings up foodstamps.html, it simply treats usa_map.svg as an image, and constructs a displayable page with the map as an embedded graphic object. This is the effect of the <object> element:


Listing 1. Reference to SVG within HTML

    <div style = "position:absolute;left:0px; top:60px">
    <object id = "map" type = "image/svg+xml" data = "usa_map.svg"
            width = "1050" height = "600"></object>
    </div>


The result is to leave your browser display looking something like Figure 5, where all 50 states and U.S. territories are one solid color. In this example, a map of the entire country (with inset maps of the Virgin Islands, Guam, and District of Columbia) is solid white in color.


Figure 5. The map before any dynamic coloring
Map of the entire United States, including its territories, all in white

Scripting interpretation starts

If your browser supports JavaScript scripting, though, that's not the end of its work. The onload browser event triggers JavaScript initialization which:

  • Stores foodstamp data in a convenient form
  • Activates the slider widget at the top of the display

Most crucially, it also acquires a handle to the DOM of the SVG instance.

Through the handle, JavaScript then can access individual elements of the SVG and specific attributes of those elements, down to the level of coloring the background of an individual state:


Listing 2. Access of SVG attributes from enclosing HTML

    function color_map(lower_level) {
        var map = document.getElementById('map');
        var svg_document = map.contentDocument;
        // Typical values for abbreviation:  'AK', 'AL', ...
        for (var abbreviation in big_table) {
            this_state = svg_document.getElementById(abbreviation);
            //  ...
            //  this_color has a value such as "red", "white", or "yellow".
            this_state.setAttribute("style", "fill:" + this_color);
        }
    }

The ID map passed to getElementById() here is exactly the ID of the object from Listing 1. The SVG instance has this ID within the HTML DOM. To reach and color an individual state, though, you navigate within the DOM of the SVG, which appears within Listing 2 as svg_document. Once svg_document is assigned, it is available for scripting in exactly the same way an isolated SVG would be scripted with document. Note, though, that document is a keyword in the sense that every browser guarantees its value, while svg_document is only a crude analogue in that its value is given in this specific program by a local assignment in the color_map function definition.


The role of SVG

How does SVG co-operate with this programming? Little is required of it; the areas of the individual states within the map are themselves given familiar IDs ('AK', 'AL', ... 'WY') to make reference easy:


Listing 3. Source of one element within SVG

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <svg
       version="1.0"
       width="958.69"
       height="592.78998"
       id="svg8834"
          ...
        <path
           d="M 486.79838,390.07686 L 488.12421,392.50754 ..."
           id="NE"
           style="fill:#FFFFFF " />
           ...
    </svg>

Notice that this SVG instance embeds no scripting. That's important enough to repeat: While this foodstamp example is inherently about scripting SVG, none of the scripting appears within the SVG source itself. To the best of my knowledge, this outside-in technique of scripting SVG has never before been clearly documented, even though different browsers have supported it for years.


SVG, HTML, and XML

To understand clearly the potential SVG has in Web applications, it's important that you recognize the subtly different role XML plays among SVG and Web specialists.

To this point, work in SVG and for the Web has overlapped surprisingly little. Although Web browsers are the most widely-distributed SVG renderers, specialists in SVG often have focused their own attention away from conventional Web applications. One consequence is a lack of documentation of "outside-in" scripting.

Another consequence is occasional confusion when Web and SVG specialists communicate about their XML bases. For Web workers, XML is an option: One can choose to think in terms of, say, XHTML, but alternatives exist. In any case, browsers are more-or-less forgiving in their HTML parsing.

That's not the case for SVG. SVG is an XML application. If a .svg source is not well-formed XML and parseable as valid SVG, then it's simply broken. Although one can speculate about a lenient SVG parser, there's no serious discussion about its desireability.

The same mass-market Web browsers that accept a wide range of HTML-like inputs generally are quite strict when rendering SVG. SVG instances and Web documents are both scripted in terms of their DOMs, and both DOMs are serializable as XML. Despite these similarities, the parsers within a single browser are generally distinct and, to some extent, must be learned separately by practitioners.


Division of labor

As interesting as the outside-in coding of this article and its applications are from a technical standpoint, their biggest impact might be managerial. It's possible to produce the same visual effect with clever Shockwave or HTML5 canvas coding. None of those alternatives make for as compelling a division of labor as the SVG technique here, however.


Better than MVC or presentation-versus-content

One of the foundational principles of software engineering is that wise designs will yield low couplings between distinct modules, which can then presumably be maintained, improved, and otherwise managed in relative isolation. This is much of the reason that model-view-controller and presentation-content partitions are supposed to be good things.

The scope of SVG is far narrower than these other partitions. However, I've found it to be particularly satisfying in my work. With the coding here, cartographic specialists can develop maps in isolation from the JavaScript coders. The linkage between the two kinds of developers is, as the previous section illustrated, just an agreement on the XML IDs of the individual geographic units. It's easy to re-use a map for an entirely different application—one perhaps not even imagined when the map was first created—or to apply the same scripting to different maps.

This weak link can be even more tenuous than might first be apparent. Different artifacts can live on different servers, for security or economic reasons, and only come together for the first time within the browser. Medical images might be coded as SVG in one country, a knowledge base of diagnoses developed in a second, and a Web application which pulls them together served up in a third.


Custom widgets

Another variation on this theme is the opportunity it opens for a marketplace in SVG-based widgets, an analogy with existing ones for JavaScript-coded libraries. It's possible to code SVG with internal scripting which creates some interesting effect, but simultaneously exposes an external application programming interface. This makes for a good way to leverage the built-in advantages of SVG—scaling, efficiency, and so on—in widget production.

In SVG, HTML, and XML, I mentioned the different roles of XML within HTML and SVG. Clarity about this distinction can help organize work. A Web developer remains perfectly free to consume SVG widgets or diagrams without having to know how to code well-formed XML himself. Conversely, an SVG specialist can develop her maps and charts without having to take responsibility for different conventions of the <embed> versus <object> distinction between different browsers.

Another kind of difference from other managerial models also deserves explanation. Languages like Java™ and C++ are often organized in terms of systems developers, who code libraries, and application programmers, who consume those libraries. Much the same is possible with SVG, and HTML5 more widely. However, the delivery artifacts for SVG, at least in 2010, are generally source code. Java technology compiles its libraries, and otherwise emphasizes information hiding. Existing practice for SVG does not protect intellectual capital with the same mechanisms. A full discussion of the implications is beyond the scope of this article.


Wider DAAS trends

As data as a service takes off, SVG will enable a wide range of visualizations which will be conveniently de-coupled from particular content. In the early days of the Web, the only facilities which provided the possibility of interaction of the sort this article illustrates were image maps and proprietary plugins. The former were notoriously tedious to write and even harder to maintain. SVG, in contrast, acts as a higher-level language for development of a wide range of graphical effects.


Other topics

While SVG is only an isolated corner of XML, it's already grown too large for any one person to know all of it, let alone capture everything in a single article. Quite a few subjects will interest readers of this article, but remain beyond its scope. For most of them, you can find good treatments readily available. (see Resources for details.)

  • Introduction to SVG, including how to write SVG instances
  • Different styles of embedding SVG images within HTML pages
  • Advanced SVG topics, including animation and construction of custom widgets
  • SVG styling, and especially the use of CSS with SVG
  • XML, and especially authorship of such artifacts for Web applications as XHTML and SVG
  • JavaScript
  • HTML5

Summary

Outside-in SVG scripting allows for advanced visual effects that are straightforward to code. The technique also encourages good modularization which minimizes the coupling between visual elements and the application logic which acts on them.


Acknowledgments

SVG as of this writing is simply a monumental achievement, one made possible only by the contributions of many dozens of thoughtful analysts and programmers. It's difficult to put into words how far they've brought SVG over the last decade.

The particular map of the United States used for this article was originally inspired by one that Wikipedia makes available under a Creative Commons ShareAlike License.



Download

DescriptionNameSizeDownload method
Bundle of sources for this articleSVG_foodstamp_tutorial.zip106KBHTTP

Information about download methods


Resources

Learn

  • Live example of map: See immediately what the article explains. If you don't see it, change browsers (see A working example above), or write me for help.

  • Render dynamic graphs in SVG (Brian Venn, developerWorks, October 2004): Scale SVG graphs based on their content with Java code that generates SVG programmatically.

  • Practical business graphing with SVG and XML (Jack D Herrington, developerWorks, July 2006): With SVG technology, create business graphs for Web pages from XML data. You use PHP to generate graphs.

  • Add interactivity to your SVG(Brian Venn, developerWorks, August 2003): Create SVG documents that respond to user input and explore SVG concepts of links, events, and scripts. These are pure responsibilities of the SVG renderer, and have no necessary relation to Web applications.

  • Dynamic SVG features for browsers (Uche Ogbuji, developerWorks, August 2006): Take a tutorial which makes the point that the stand-alone interactivity of SVG can benefit Web pages.

  • SVG Tutorial from w3schools.com: Check out this quick-and-easy tutorial which emphasizes simple examples.

  • SVG Home Page: Visit this center of SVG information created and maintained by the World Wide Web Consortium which has responsibility for Scalable Vector Graphics as a standard.

  • XML DOM tutorial: Get a good foundation in DOM with this W3C-sponsored tutorial. In broad terms, client-side scripting addresses the DOMs of the pertinent sources, including, for this article, any SVG.

  • The svgweb home page: "SVG Web is a JavaScript library which provides SVG support on many browsers ...". Browsers increasingly support SVG as installed, without external plugins or libraries. If you're in a situation where you must support an obsolete browser, though, learn how SVG Web can be a project-saver.

  • Google Chrome Frame: Explore an open-source browser plugin, similar to SVG Web. Google Chrome Frame does both more and less than SVG Web. Google Chrome Frame's only target is Internet Explorer (Version 6, 7, or 8); on the other hand, its scope is wider, extending beyond SVG to support a broad range of HTML5 constructs, including canvas.

  • The W3C's Scripting Primer: Try this single best developer guide to SVG. It even has a section entitled Scripting between HTML and SVG, the subject of this article—but focuses entirely on "use [of] HTML to modify SVG [rather] than vice versa."

  • Introduction to XML (Doug Tidwell, developerWorks, August 2002): Set the stage so you can understand SVG as an XML application. Much of the daily work of managing SVG development simply inherits from broader XML principles, and it's important to understand XML clearly before tackling SVG.

  • While knowledge of CSS is more dispensable to SVG comprehension than is XML, the former plays a significant role in most practical SVG applications. Cascading Style Sheets (CSS) (developerWorks, Apr 2007): Read this introduction to CSS for XML applications such as SVG and see how to specify presentation characteristics for XML documents.

  • XML Matters: Program with SVG (David Mertz, developerWorks, April 2005): Make the most of SVG scripting and animation with this installment of the "XML Matters" column.

  • Animation - SVG 1.1.: Read the current authoritative W3C reference on SVG animation

  • The future of HTML, Part 1: WHATWG (Edd Dumbill, developerWorks, December 2005): Read an early introduction to the concepts and motivations of HTML5.

  • SVG: object or embed?: Five different HTML elements embed SVG within HTML. While the author doesn't know of a recent write-up on their use, read this 2002 comparison of object and embed by Damian Cugley, that also mentions the other three alternatives.

  • Compatibility tables for features in SVG and other aspects of browser rendering: Check out when to use various features in HTML5, CSS3, SVG and other upcoming Web technologies in these tables by Alexis Deveria.

  • Flash and substance (Peter Seebach, developerWorks, June 2006): Read about some of the liabilities of Flash and other proprietary approaches to graphics on the Web. Also, see what Loren Baker and Jakob Nielsen think about it.

  • Cameron Laird's personal page on'Net-accessible data sources: Start with the author's personal page on data sources to pursue choropleths and other representations of econometric data such as the foodstamp coverage this article uses as an example. An immense wealth of information on visualization, cartography, and datasets is available across the Web. Foodstamp participation rates for the summer of 2009 appear in Food Stamp Use Rises in Rural and Cities and a variety of government publications.

  • References on SVG: Visit the personal SVG page maintained by the author. The page includes information on policy, future prospects for SVG, and other matters.

  • XML area on developerWorks: Get the resources you need to advance your skills in the XML arena.

  • SVG articles and tutorials on the developerWorks Web Zone: Explore a variety of client- and server-side techniques which are available to generate SVG dynamically, and manage it as a part of a larger Web page.

  • IBM XML certification: Find out how you can become an IBM-Certified Developer in XML and related technologies.

  • XML technical library: See the developerWorks XML Zone for a wide range of technical articles and tips, tutorials, standards, and IBM Redbooks.

  • developerWorks technical events and webcasts: Stay current with technology in these sessions.

  • developerWorks on Twitter: Join today to follow developerWorks tweets.

  • developerWorks podcasts: Listen to interesting interviews and discussions for software developers.

Get products and technologies

Discuss

About the author

Photo of Cameron Laird

For long-time developer Cameron Laird, "graphics" has, on different occasions, meant everything from images of brains scans and aircraft cockpit displays to pipeline control boards and commodity market charts. He's an enthusiastic Invited Expert to the SVG Interest Group precisely because SVG promises to relieve so many problems common to these diverse domains. Cameron also is a prolific author of articles for developerWorks and other professional publications, as well as the Smart Development blog. Cameron consults as vice-president of Phaseit, Inc., which he co-founded, and can be reached as claird@phaseit.net.

Report abuse help

Report abuse

Thank you. This entry has been flagged for moderator attention.


Report abuse help

Report abuse

Report abuse submission failed. Please try again later.


developerWorks: Sign in


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Select information in your profile (name, country/region, and company) is displayed to the public and will accompany any content you post. You may update your IBM account at any time.

Choose your display name

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


Rate this article

Comments

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=XML, Web development
ArticleID=478807
ArticleTitle=Create client-side diagrammatic interaction in Web applications with SVG
publish-date=04062010
author1-email=claird@phaseit.net
author1-email-cc=dhatten@us.ibm.com