Surviving the Zombie Apocalypse with HTML5 and SVG, Part 2: Text, Paths and Basic Animation
Justin Whitney | February 11, 2013
The first article in this series covered the basics of SVG, an overlooked, underappreciated aspect of HTML5. While different browsers implement SVG in different ways, the previous walkthrough described how to create text, incorporate SVG images and build basic shapes such as circles, polygons and paths in a way that all browsers recognize.
The result was the start of quite possibly the world’s first SVG-driven Zombie Apocalypse Survival Predictor. Thus far, the page is pretty (ish) but completely nonfunctional. To take the page to the next level, this walkthrough delves deeper into paths and their myriad uses, demonstrates how to build the prediction meter and touches on some basic animation to add that little extra to the page (for the browsers that can understand it).
The Text Element (Continued)
Take a closer look at SVG text. In Part 1, the <text> element was used within an <svg> block for the page title. It shares the same styling attributes as HTML text, but instead of using the “style” attribute to enumerate them, the example used individual elements for maximum cross-browser compatibility.
This example should display correctly in every browser, but it doesn’t even scratch the surface of what sets SVG text apart from regular text.
The transform Attribute
To start, consider the “transform” attribute. Previously, this attribute was used to shrink SVG images to their proper sizes, thusly:
However, the attribute can also be applied to <text> elements. For instance, using the “rotate” transform adds a little tilt to the title:
This says, “at the coordinates 100,100, rotate the text 30 degrees (clockwise).” The result should look like Figure 1.
The transform attribute includes several other possible values:
These transformations apply to other SVG objects as well, as demonstrated by the <image> scale transform. Transforms can also be nested by listing them in the order of the transforms you want. For example, note the result of the following code in Figure 2. Two words in the same position, with the same transformations, but applied in reverse:
For more information, read the W3 spec on the transform attribute.
The tspan Element
In the previous example, two separate <text> elements were created so that transformations can be applied to each word. However, within <text> elements with common styling and transformations, nested <tspan> elements can be used to define individual attributes, such as position and color.
In addition, position can be defined either absolutely (x,y) or relatively (dx,dy). Combined with <tspan>, this sets up some interesting text tricks. Note the use of absolute and relative coordinates in the following example, illustrated in Figure 3.
One neat trick that the origin coordinates enable is to specify multiple coordinates, which then get applied to each letter. While this can be done with absolute coordinates, it’s a bit easier with relative coordinates, especially when applied to an individual <tspan> element, as in Figure 4. (The “letter-spacing” attribute has also been applied in the following example to give the letters a little breathing room.)
Going back to the original “cityBox” element created in Part 1 of this series, apply the “rotate” transform to the text as a whole, and the multiple relative Y-coordinates to the last word. Now the terrified little human has something to run from, even before adding the zombies, as you can see in Figure 5.
The Animate Element, or Introduction to SMIL
Before leaving the title alone in peace, there’s one more interesting trick that can be applied to it for dramatic effect: the <animate> element. This one, however, is not cross-browser compatible.
Like SVG, Synchronized Multimedia Integration Language (SMIL) has been around for a while, with v1.0 becoming a W3C Recommendation in 1998. It essentially provides animation markup for text and media. Since the same working group that developed SMIL also worked on aspects of SVG, the latter incorporates certain features defined in the SMIL spec.
To date, not all browsers recognize SVG animation via the SMIL spec. However, those that don’t will simply ignore it rather than break. So consider animation a nice treat for a subset of users. (See “Can I use…” for a complete list of browsers and versions that recognize SMIL animation.)
The primary elements making up SVG animation include <animate>, <set>, <animateMotion> and <animateTransform>. Many browsers still recognize <animateColor>, though that element has been deprecated in favor of <animate>.
To use SMIL animation, the element should be nested within the SVG element being animated. In this example, the stroke color of the title text will be animated (attributeName). It is set to begin 2 seconds after being loaded, last 10 seconds (dur), and go from black to red. The animation is then set to freeze on its end state by setting fill=”freeze” (not to be confused with fill color).
If viewed in a compliant browser, this results in a slow, subtle effect suggestive of bleeding text. (Skip to the sample page listed at the end of this walkthrough for a demonstration.)
The Path Element
Part 1 of building the Zombie Apocalypse Survival Predictor covered the basics of creating a <path> element. While different elements exist for different types of shapes, such as <polygon> and <rect>, the <path> element can be used to create these same shapes. Not mentioned last time, the Closepath (Z) command facilitates closed shapes by drawing the final leg automatically, as in this snippet, which is illustrated in Figure 6:
But Paths can also do much more, from creating simple lines to setting the baseline for text to defining a motion path for animation.
Creating Straight Lines
As shown in the preceding snippet, a line consists of nothing more than the Moveto (M) or starting point and the Lineto (L) or connecting point. The following creates three consecutive lines of varying stroke widths:
These use absolute coordinates to define precise placement of the line nodes. However, relative coordinates can also be used where it makes more sense by using lowercase “l” for Lineto. The following creates an identical set of lines as the above example (and, as a bonus, note how the “style” attribute is replaced with individual attributes so that the stroke color can be set for the entire group instead):
In this case, rather than defining a Lineto coordinate of “175,100”, for example, “l 75 0” says “Draw a line to the right for 75 points.”
If you’re drawing multiple lines of the same style, the relative Moveto (m) can be used the same way by establishing the first origin, then adding new relative origins in the same <path> element. In this way,
is identical to
When you’re drawing vertical or horizontal lines, things get even easier. The Horizontal Lineto (H or h) and Vertical Lineto (V or v) commands reduce the coordinate to a single dimension, either absolute (H or V) or relative (h or v). The following draws the same three lines as the earlier examples (note, too, the elimination of superfluous whitespace between the commands and numbers):
In addition to all the straight lines, paths can create curvy lines. In fact, the <path> element includes multiple commands for implementing curves:
Since curved paths are not strictly necessary to escape from zombies, they won’t be covered here. For more information, see the W3C spec on <path> curve commands.
Creating the Prediction Meter Pane
With <path> basics covered, what this Survival Predictor needs is an actual meter. So, before adding any new elements, add a third pane to the two panes created in the previous walkthrough. First, change the previous id style from “#controlPanelBox” to a class style, “.svgBox”. For now, the panes will have borders for visibility.
Also be sure to add the class to the controlPanelBox <svg> element:
Create a new element of the same class to serve as the container for the prediction meter:
This meter will be pretty basic, consisting of some simple shapes, such as thermometer tics and a pointer that will eventually be repositioned based on the prediction algorithm. It will also include a button that will be made interactive in the last article in this series. For now, add a text label and some groups to contain the other elements:
With SVG objects, order counts. Since the tics will be on the bottom of the stack, draw those now. Prior to this walkthrough, those lines may have looked something like this:
However, by pulling stroke information into a group element, as well as using relative Movetos and Horizontal Linetos, this code can be reduced:
Beneath the tics but within the oddsMeter group, draw a triangle like the one used in the control panel. Only this time, since it’s a single object and won’t need to be duplicated, use the <polygon> element:
This element is contained within the oddsMeter group, so a new stroke width is specified to override the group’s stroke-width attribute.
Last, add a rounded rectangle at the bottom of the same group, which will cause it to appear on the top of the stack. The <rect> element hasn’t been used yet in the Predictor, but its attributes are self-explanatory. Note the radius-x (rx) and radius-y (ry) instructions for creating the rounded corners:
Below the meter, add the button for calculating the odds of survival. The button consists of two SVG elements, <text> and <rect>, ordered so that the text appears on top of what is essentially a white-filled rectangle. What’s important to consider here is that when interactivity is added later, it needs to be added to the button as a whole, which is why these two elements are grouped and named. Otherwise, adding an event handler either to the text or to the rectangle behind it could produce unsatisfactory user interaction. Grouping them also provides an easy mechanism for adding a cursor:
The finished prediction meter panel should look like Figure 7.
Creating a Text Baseline
As previously mentioned, paths can also provide a baseline for <text> elements. To see this in action, go back to the title in the “cityBox” SVG element, which currently looks like Figure 5. Rather than apply a “rotate” transform, we’ll fix the baseline of this text to a basic path.
First add a crooked path at the top of the “cityBox” SVG pane. Go ahead and include a black stroke for now (stroke weight will default to 1). Since this is not a straight line and can be seen as a potential polygon, set fill to “none”. Give it the name “titlePath”, which will be referenced in the next step. By default, if the path is not long enough to serve as a baseline for the entire text, any remaining text will be truncated, so this path is given an extra-long leg at the end: “l250 100”.
The path, without the additional elements, should look like Figure 8.
To anchor the text to the path, nest the text content and any <tspan> elements within a <textPath> element, which itself is nested within the <text> element. The <textPath> element then specifies an xlink referencing the path. (While you’re at it, remove the transform and switch the path’s stroke color to “none” to render it invisible.)
Unfortunately, here’s where browser differences poke their ugly, rotting head. Some browsers ignore the “x” attribute and position the text to the baseline according to the “text-anchor” attribute. Other browsers ignore the “text-anchor” attribute and position the text to the baseline according to the “x” attribute. So, to find a fix that works on both, change text-anchor to “left” and x to “15”:
The universal result should look something like Figure 9.
Creating an Animation Path
Though the full potential of the <path> element has not yet been plumbed, nor will it be in this walkthrough, it can be used to add one more bit of sizzle. Similar to the way a path can provide a baseline for text, it can also provide a baseline for animation. The caveat here is that this falls under the heading of SVG/SMIL animation, so it is not fully cross-browser compatible. Again, consider it a bonus for browsers that recognize it since it doesn’t break anything for those that don’t.
In Part 1, the control panel pane included a toggle for Zombie Speed, as rendered in Figure 10:
To have a little something extra, it would be interesting if those zombies were actually moving around. To do that, two sets of new elements will be added: invisible paths and the <animateMotion> element, which is similar to the <animate> element used in the title.
Before making the zombies walk, or rather shamble, it’s helpful to know how animation paths work, since it’s not necessarily intuitive. The key difference between using a <path> element for animation and using one for a text baseline is that the path does not define its target element’s actual placement on the page, but rather its relative movement.
To explore this, create an empty <svg> element of the class “svgBox” with dimensions 400 by 400. Add a simple circle and a path:
In this example, the goal is to move the red circle from 100,100 to 300,50. So a path is placed starting at 100,100 and ending at 300,50. To add motion, open up the <circle> element and add the <animateMotion> element within it, with a duration (dur) of two seconds. Then add an <mpath> element within that specifying the path name as its xlink reference:
When the page is loaded (in an animation-friendly browser), something interesting happens. Instead of moving along the path from 100,100 to 300,50, the circle jumps down to 200,200 and moves to 400,150, which brings it halfway out of the <svg> container. This occurs because of how the <path> element’s instructions are interpreted. Regardless of whether it’s absolute or relative, the path’s initial Moveto instruction gets applied as a relative placement for the element being animated. So in this case, the first thing that happens on page load is that the circle, with an origin of 100,100, gets moved +100, +100 before movement begins, based on the path’s “M” value.
This is easy enough to work with. For paths used in animation, simply start them at 0,0, the only drawback being that the path becomes a little trickier to develop and debug since, as in this example, it may extend out of the <svg> element:
Now the circle moves as expected relative to its starting origin. In fact, because animation paths define relative movement, the circle can be moved to a different origin entirely and will still move in the same way at its new location, without having to modify any <path> values.
Now, zombies. First, create the paths that will be used. The goal here is for the zombies to move within the confines of their underlying <circle> elements. Since the paths need to start at 0,0 and will include subtle Lineto changes, the easiest way to refine the movement is to go ahead and implement the animation, then make adjustments through trial and error.
In the following revised code for the Zombie Speed toggle, two paths are added with approximately the same number of points. The key difference here is the duration of the <animateMotion> element: Walking Dead zombies take four seconds to complete the path, while World War Z zombies take half a second. Also, a “repeatCount” attribute of “indefinite” has been added to create an endless loop.
The result: the Zombie Speed toggle gives the user additional visual information about the function of the buttons and what their impact may be. Shamble vs. rage. Romero vs. Snyder. It’s right there on the page.
At this point, all of the basic visuals of the Zombie Apocalypse Survival Predictor are in place, plus a few bells and whistles. The <text> element has been explored more deeply, and the <path> element has gotten a lot of love as well. The updated Predictor uses it not only to draw lines and finish out the UI but also to provide a baseline for the title and animation paths for the zombie icons.
The code thus far can be seen in action
This article is part of the HTML5 tech series from the Internet Explorer team. Try-out the concepts in this article with 3 months of free BrowserStack cross-browser testing @ http://modern.IE
About the Author
Justin Whitney builds Web sites and mobile apps in a bunker in rural East Texas while prepping for the end of civilization.