ScalableVectorGraphics
Volume Number: 16
Issue Number: 2
Column Tag: Emerging Technologies
Scalabe Vector Graphics: An Introduction for
Programmers
by Kas Thomas
Learn how this important new web document
standard will impact web design and (quite possibly)
OS X imaging
The World Wide Web is primarily a visual medium, and the primary unit of
information display on the web today is the page - the web page. But despite rapid
progress in offline document technology, the web page continues to be based on an
archaic imaging model. The HTML (Hyper-Text Markup Language) display technology
upon which 99% of the world's web pages are built was never designed to accommodate
48-bit color, realtime animation, on-the-fly antialiasing, infinite zooming, vector
art, embedded Type 1 fonts and professional typography, pixel-accurate positioning of
page elements, or any of the other DTP-inspired features modern computer users have
come to depend upon in their daily work. In order to make high-end display features
like these possible in HTML, nothing short of a complete rewrite of the HTML document
model would be needed.
Fortunately, that rewrite has just been completed by the World Wide Web Consortium
(W3C) and is now ready to enter service. The formal standard is called Scalable Vector
Graphics (SVG) and can be found online at <http://www.w3.org/TR/SVG>.
Far more than just a graphics standard, SVG is a full XML grammar (with a public
Document Type Definition) and an associated XML namespace, meaning that SVG can
encapsulate not only images or text, but standalone documents. You can embed SVG files
inside HTML pages using the traditional
pages as freestanding '.svg' files (providing your server is set up to serve such files
with a MIME type of 'image/svg'). Any well-formed XML file can embed SVG, and
(conversely) any SVG file can embed well-formed XML - including SVG itself.
In the coming weeks and months, you're going to be seeing and hearing a lot more about
SVG. In fact, SVG has even been mentioned as a possible basis for a future QuickTime
Image Importer (something that, if it happens, will probably happen in the next 12
months); and in a talk given at WWDC last Fall, Apple's Peter Graffagnino (Director of
Graphics and Imaging Software) hinted that developers targeting OS X might want to
consider providing native SVG support in graphics programs.
Given the increasingly significant role SVG is likely to play not only in web graphics
but in desktop graphics, now might be a good time to become better acquainted with
this exciting technology. In this article, we'll look at SVG first as a document standard,
with a view to understanding how its pieces fit together for maximum cross-platform
interoperability. We'll have time to say a word or two about forthcoming tools for
working with SVG; then we'll take a look at raw SVG code and try our hand at some
JavaScript animation effects in SVG. We've got a large amount to cover in a short
space, so let's hit the ground running.
What Is SVG?
In a strict markup-language sense, SVG is any XML document that adheres to the
document type definition at
(or equivalent more recent version) and conforms to the rules set out in the standard
at . But SVG is more than just a tagset and a grammar
for associating styles and attributes with graphics primitives. It's a philosophy for
how text and graphics information ought to be encapsulated, manipulated via code, and
rendered to output devices at runtime.
In a way, Scalable Vector Graphics is a rather peculiar moniker, with a redundant ring
to it, kind of like "Peelable Yellow Bananas." After all, vector graphics are by nature
scalable (i.e., capable of being enlarged or reduced indefinitely without resolution
loss); you wouldn't think that point needed reinforcement. But maybe it does. We're all
so accustomed to seeing GIF and JPEG files in fixed resolution on our browser screens
that the thought of web graphics being infinitely zoomable (much less rotatable or
draggable) hardly seems natural.
Vector graphics lend themselves to rescaling because they are not predrawn at any set
size, as JPEG, TIFF, GIF, and other bitmapped images are. Instead, vector art is
rasterized at the last possible minute, on the user's machine, using the maximum
appropriate pixels-per-inch resolution for the output device in question, even
including supersampling to achieve antialiasing. It's this peculiar characteristic of
"late pixel binding" that gives vector graphics its versatility and power. When you
virtualize your art elements - dealing with them in the abstract, drawing them only at
the last minute ("just in time") - you can set up your render pipeline to perform any
number of coordinate-space manipulations, alpha-channel operations, opacity ramps,
blends, masks, clips, warps, morphs, overlays, etc., in any combination, without the
slightest bit of resolution loss, because you haven't drawn anything yet. Once all the
vector-space manipulations are complete and the user has chosen an output resolution,
monitor mode, zoom factor, and so on and so forth, rasterization can begin. Then the
image gets drawn - at the highest level of perfection attainable.
PostScript aficianados will recognize the concepts described here as inheriting
directly from pioneering work done by Warnock and Geschke in 1984. The same
concepts underlie PDF (as well as Adobe Illustrator and Macromedia Flash). But
rather than using the postfix notation of PostScript, SVG uses ordinary
markup-language tags to encapsulate drawing information, so that, for example, to
draw a red-filled circle of radius 25 at an x-y position of [100,100] on the screen,
one need simply do:
In the circle tag, the cx and cy attributes give the centerpoint coordinates of the circle
in the current coordinate space (which by default has its origin at the top left corner
of the browser window or current viewport, with 'y' increasing in the downward
direction), 'r' gives the radius (in pixels, unless another unit system has been
defined), and the style attribute specifies how the circle should be drawn.
The various built-in SVG geometric primitives and their associated tags and attributes
are shown in Table 1.
Shape Required attributes
›cx, cy (center point coordinates) r
(radius)
›cx, cy (center point coordinates) rx
(radius in x), ry (radius in y)
›x, y (coordinates of the top left corner)
width, height (rectangle's dimensions) optional: rx, ry (radius of corners, if it is to
be a "rounded rect")
›x1, y1 (coordinates of starting point) x2,
y2 (coordinates of ending point)
›points (pairs of numbers signifying the coordinates of points on a line)
›points (pairs of numbers signifying the coordinates of points on a line)
›A,C,H,L,M,Q,S,T,V,Z operators, plus coordinates or numeric offsets. (Note that capital letters denote absolute-coordinate
operations; lowercase denotes a relative operation.) The
various operators stand for:
A elliptical arcC cubic bézier curvetoH horizontal linetoL linetoM movetoQ quadratic
bézier curvetoS smooth cubic bézier curvetoT smooth quadratic bézier curvetoV
vertical linetoZ closepath
Table 1. SVG Drawing Primitives.
You'll notice that whenever a parameter value is called for, it is given between
quotation marks. (Also note that the ending tag is a forward slash followed by a
greater-than symbol.) In general, the arguments and parameters to a drawing element
aren't called arguments and parameters, but attributes and values. The attribute is the
thing on the left side of the equal sign (such as cx), while the value is whatever is
between quotation marks on the right side.
Lest you get the idea that SVG is simply a vector-graphics engine, bear in mind that
you can embed bitmapped graphics inline in an SVG file using almost the same syntax
you would use for putting GIF or JPEG images in an HTML file. An example of the
syntax is:
xlink:href="mypic.png">
The 'x' and 'y' attributes refer to the position where the top left corner of the
bitmapped image should appear. The 'width' and 'height' attributes describe the
dimensions of the destination viewport for the image (in this case, in pixels). You'll
notice that the URL is referenced with an 'xlink:href' tag instead of the more familiar
'href' notation. This is the XML way of denoting a link to an external URL. All links -
even to anchors within the host document itself - are treated this way in an SVG file.
The image file in this example is a PNG file: an image in the Portable Network
Graphics format. This is one of two bitmap formats SVG supports, the other being
JPEG. What about GIF? As it happens, there is no support for GIF. That doesn't mean
that shipping software products that support SVG won't incorporate GIF support; some
no doubt will. The formal SVG specification doesn't require GIF support, however. The
reason for this has to do with patent rights. The Graphics Interchange Format
(developed originally by CompuServe) uses Liv-Zempel-Welch compression as the
default compression method. It turns out that this compression method is covered by a
patent that Terry Welch took out in the mid-1980s on behalf of his employer at the
time, Digital Equipment Corp. Through a series of corporate acquisitions, the patent
ended up with Unisys, which in recent years has been sending its minions around to
make sure users of the LZW algorithm pay royalties on it. This was enough to convince
the W3C to abandon GIF support in SVG. Even though the Welch patent expires in
2003, there will - for now - be no formal requirement for GIF support in SVG.
In a greater sense, it doesn't matter, because PNG, which was developed specifically to
replace GIF, is a big win for all concerned. Its feature set (which includes
sophisticated lossless compression, alpha transparency, interlacing for progressive
download viewing, onboard gamma adjustment, advanced checksum and
corruption-detection techniques, and much more) goes well beyond GIF's capabilities,
and since the source code is freely available, consistent implementation of the feature
set is virtually guaranteed. (For more information on PNG, see
.)
If you're worried about not being able to offer advertisers on your site the ability to
use animated GIFs, relax. There's something much better in store: namely, animated
SVG. (We'll get to that in a minute.)
SVG's greatest visual impact on the World Wide Web, paradoxically, may very well
come in terms of text. With SVG, a page containing mostly text (and let's face it, most
web pages are primarily text) can be professionally typeset, drawing (if you'll pardon
the pun) on Type 1 fonts in any size, style, color, or leading. Also, just as with PDF,
fonts don't need to be present on the user's machine in order for a page to be imaged
properly. Externally linked font resources can be supplied, and - if need be - the
browsing application can retrieve needed resources from the appropriate URL(s) in
real time.
What it means is that web pages, if written in SVG, could end up looking a lot more like
magazine pages and a lot less like TTY emulation, with text that is zoomable (and
properly antialiased) yet doesn't reflow every time the window is resized.
In SVG, text takes two forms: its ASCII (or Unicode) encoded form, and its
stroked/filled form. The encoded form is always present inside the file, where it can
be traversed by search engines. But most of the time, we're really talking about the
graphical representation of text: fill color, stroke color, size, opacity, character
width, and so on. Remember that in SVG, as in PostScript and PDF, everything that gets
painted to the screen (except for inline PNG or JPEG graphics) consists of stroked
and/or filled paths. That includes font characters, which are just closed bézier-curve
paths.
Specifying text in an SVG file is almost as easy as specifying text in an HTML file. For
each text element, you simply do something like this:
style="fill:black;font-family:Helvetica;font-size:18">This is 18-point
Helvetica.
The text in this block - which says "This is 18-point Helvetica." - will be drawn one
inch (72 pixels) from the left side of the viewport and two inches (144 pixels) down
from the top. The style attribute contains property:value pairs for fill color (black),
typeface (Helvetica), and type size (18 points). Note that text blocks must be
terminated with a closure.
As you can see, this is not a terribly difficult syntax to master. The only part that may
cause some consternation is the fact that each line of text you put on a page has to have
a specified starting position. Text doesn't wrap automatically. . This is either a
blessing or a curse depending on your outlook. For most users, most of the time,
line-wrap won't be a problem, because most users will rely on commercial authoring
apps (such as Adobe GoLive, which will feature full SVG support) to produce
line-wrapped SVG text automatically. Even Adobe Illustrator (which has an SVG export
plug-in) does a fair job of justifying large blocks of text. It's only at the (low) level
of hand-crafting your own SVG files in a text editor that you have to "sweat" things
like line breaks, tabs, and interline spacing (leading).
Styles
SVG supports inline, embedded, and/or external stylesheets under CSS2 (the standard