Scalable Vector Graphics will let you draw graphics using inline code...and it's efficient!
Last week we got a quick glimpse at some of the power and promise contained in the World Wide Web Consortium's latest XML-derived webdoc standard, the soon-to-go-primetime SVG (Scalable Vector Graphics). We noted that contrary to what the name implies, SVG is not merely a graphics engine but rather a fully CSS-compliant, Unicode-ready document standard with all the power of XML, Cascading Style Sheets, and stroked/filled vector graphics contained in one flexible, easy-to-use XML tagset. Plus, like any good markup language these days, SVG adheres to the Document Object Model, which means every element inside an SVG doc is reachable from JavaScript. This, in turn, opens the door to scriptable animation, while also putting a moveto( )/lineto( ) graphics engine at the disposal of JavaScript programmers.
This week I want to show you what real, working SVG code looks like, and at the same time, make good on my earlier promise that you don't need anybody's fancy SVG authoring software to create SVG docs, because in actuality, any ordinary text editor will do. Without further fuss, let's take a look inside a small (yet fully functional) SVG file designed to produce a graphic similar to the one shown below:
Before we walk through the code, I want to remind you that this file can constitute its own standalone Web page (for any browser that can recognize the mime-type 'image/svg'), or it can be incorporated into any HTML page using the <embed> tag. When embedded in an HTML file, the graphic is drawn inline, at that point in the file, the same way a JPEG or GIF image is.
Code Walkthrough
The opening line of the SVG file, beginning with '?xml version="1.0"...', identifies this as an XML file encoded in ASCII (that's what the reference to iso-8859-1 means). The second line, which starts with !DOCTYPE, gives version information and the URL where the Document Type Definition can be found.
The rest of the file is inside <svg></svg> tags. The opening <svg> tag gives the image's overall dimensions (which can be cropped or overridden from the embedding HTML page), along with information on how to treat whitespace characters. (In this instance, spaces are preserved rather than, say, collapsed.)
If you look at the remaining code, you'll see that it's really in two chunks: a chunk surrounded by <style></style> tags, and a chunk shrouded in <g></g> tags. The first segment represents style information, obviously. The second grouping is where the drawable elements occur.