Draw by Numbers with SVG

Designs for UI widgets often incorporate shapes of such geometric simplicity that it seems a shame to spend the effort, disk space, and bandwidth of creating, storing, and delivering bitmaps for them.

Think of the dots used to indicate a reader’s position in a sequence, or the triangle tips protruding from popovers, pointing toward their referent.

walkthrough-svg-examples

In these cases, I’ve taken to simply writing the graphic out as an SVG one-liner. SVG is a format for specifying vector graphics and is technically human-readable—even if the long sequences of coordinates can become fairly mind-numbing in advanced usage.

Hand-writing SVG markup

In fact, on Splice, we use SVG one-liners for precisely the above examples.

Here’s one of the dots:

<svg class="dot" width="8" height="16">
  <circle cx="4" cy="8" r="4" fill="#dddddd" />
</svg>

circle is among the more readable svg tags. It has a center (cx and cy) a radius (r), and a color (fill).

CSS even makes a rare excursion beyond its usual domain of content markup into the shape world of SVG: you can override the fill color (but not other attributes, that I can tell) with CSS rules.

.dot circle {
    fill: #333333
}

Drawing SVGs programmatically

Beyond just letting us replace bitmaps with drawing commands, as a domain-specific language for geometry, SVG opens up avenues for programmatically generating more sophisticated shapes, or ones with variations or animations.

For example, here are the sprites for a sprited loading spinner we have been toying with in-house:

spinner-sprites

The above was generated in pure JS with just a few lines of trig. Take it for a spin.

While you do, stay a while and try your hand at a few shapes. Or forget your hand and imagine yourself a turtle tracing lines in the sand. Children of the ’80s know what I’m talking about.

June 26, 2014