Sonic is a small (~3k minified) JS “class” you can use to create custom loading animations. It works best with looping animations — i.e. a snake that’s trying to eat its own tail.

Sonic uses the HTML5 <canvas> element/API. It works by drawing a shape (by default a 6px square) at tiny intervals along a pre-defined path. You can define the path using the functions: arc, bezier and line.

A really basic example is a square (four lines):

var square = new Sonic({
 
    width: 100,
    height: 100,
 
    fillColor: '#000',
 
    path: [
        ['line', 10, 10, 90, 10],
        ['line', 90, 10, 90, 90],
        ['line', 90, 90, 10, 90],
        ['line', 10, 90, 10, 10]
    ]
 
});
 
square.play();
 
document.body.appendChild(square.canvas);

View this example

You don’t have to make up the path with a series of tiny squares though. You can do whatever you want. Another step function that comes with Sonic is fader, which draws interconnecting paths along the main path. This in combination with an arc works quite well:

var circle = new Sonic({
 
    width: 50,
    height: 50,
    padding: 50,
 
    strokeColor: '#000',
 
    pointDistance: .01,
    stepsPerFrame: 3,
    trailLength: .7,
 
    step: 'fader',
 
    setup: function() {
        this._.lineWidth = 5;
    },
 
    path: [
        ['arc', 25, 25, 25, 0, 360]
    ]
 
});
 
circle.play();
 
document.body.appendChild(circle.canvas);

View this example

You can also define your own step function. This is really what I would recommend since the default ones (fader and square) are somewhat limited.

You might be thinking that I should have called it Snake instead of Sonic, but really, there are so many possibilities that Snake wouldn’t have made sense.

To see what Sonic can really do, visit the demo. Sonic is on github too.

Update: cadc on github has made SonicGIF which generates animated GIF images for you to use in older browsers.

Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!