Spirographs and SVG

Published 03 April 2016

Virtually everyone knows Scalable Vector Graphics (SVG)- they look good at any scale, they are easy to write or draw, and look a bit like HTML. What not many people realize is that, like HTML, they support Javascript and data URLs. This means that you can put an entire little application in a single SVG file. This is pretty cool, to say the least, because a lot of sites which won’t take Flash or Canvas application will happily accept SVG as just another image. Also, anyone with the file can open it in a browser and it’ll work, with very few exceptions. You can have any sort of interactivity you can write with Javascript in the SVG, as well as a lot of useful SVG-specific things. Such things include an extensive animation API (e.g. easy fade in/out), better positioning than in HTML, and graphics primitives like polylines. For simple interactivity, you don’t even need Javascript. It’s very flexible and easy to use, to boot. So long as your users aren’t on IE9 or below, you’re in good shape. Just make sure to use an <object> or <embed> tag to get interactivity to work.

All of that said, editing a file filled with Base64-encoded blobs of PNG, XML floating about and mixing with Javascript, and chunks of precomputed JSON is a pain. Trying to update a single PNG means tediously reencoding it, then pasting it into a already large and complicated file. However, Jekyll can save us here. Between includes and plugins, you can write a bunch of simple, clean files, edit them each with your prefered editor, and let Jekyll combine them all into the monstrosity you will eventually publish. I mentioned plugins: by default, Jekyll has no way to Base64 and include images. It does, however, have an excellent plugin API. I found this one, which works very nicely, with a little configuration. In short:

  1. You have to just download the .rb file in lib, as it seems not to work as a gem install.
  2. It needs mimemagic- you can install it with gem install mimemagic
  3. It doesn’t work, at least on my system, because it does not look at the right paths. I fixed this by editing the file; you can download my edited version here. Again, this needs to go into the _plugins directory.

Two little examples I put together:

Interactive spirographs written using SVG and Javascript, with just a hint of CSS. Try clicking on a drawing head.

A little physics thing. Try clicking on the background and on the objects. If you look at the code, the ‘TEST’ image is in there as a large base64 blob.