Sexy animated spirographs in 35 sloc of d3.js

You probably remember spirographs as kid’s toys from your youth. I had a simple set that was just a collection of plastic sprockets with holes for pencils.

Endless amounts of fun when I was two or three years old. I think … I don’t really remember much from that time, but I remember having those thingies and loving playing with them. One of my earliest memories even!

Last night I was making an animation example for the d3.js book I’m writing and ended up with the idea of progressively drawing out cool looking parametric equations. Little did I know, those are actually spirographs! Learned something while I was learning something.

My failure in common knowledge aside, it’s possible to animate the drawing of parametric equations with just a few lines of d3.js code. What I’m about to show you has a pretty big problem, but produces cool looking results “in the lab”. Try to guess what the problem is.

Animating spirographs

After a few steps

We’ll make an animation timer and for each tick we’ll draw a new step of the spirograph. After the spirograph is finished, we’ll stop the timer. To make the animation more interesting to watch, we’ll also fake a brush flying around (just a black dot).

I found the parametric function in the wikipedia’s article on parametric equations. We’ll be giving it a simple parameter calculated from the animation timer and it will return a two dimensional position.

This is our step function. It draws every consecutive step of the animation by moving the brush and putting a line between the current and previous position. The animation will stop when this function returns true so we make sure the time parameter doesn’t go beyond t_scales‘s domain.

Finally, we simply start the timer.

var timer = d3.timer(step,500);

The timer will start running after 500 milliseconds and repeatedly call the step function until it returns true.

The problem with this approach is that I’m using the animation timer itself as a parameter to the function, which means point density depends on how long you’re willing to let the animation run. It will always draw the complete function because of how d3 scales work, but it might look very approximate. Think squares for circles approximate.

Another problem is that using a slower computer, or doing anything that lags the CPU even a little bit while the animation is running will ruin the final picture.

For instance, this is what happens when I switch desktops around while the browser is drawing.