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); |
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); |
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!
Great share James 🙂
awesome!cool~
No IE support?
m/ Bindass !
can you list the browser support?
thnx
It’s cavnas-based, so IE9 and above only. Use a feature test for canvas and an then an animated gif as a fallback.
Looks great. Please go for all browsers. It will be great to have nice loaders.
How on earth do we do these though James, they all have the same class, so very difficult to isolate one particular loader, they are awesome by the way…
But I am referencing your master dem, with 9 loaders, I love the middle row, far right loader, the one with orange and blue animated lines ..
How do I isolate just the code for this particular loader.
Ste
@Steve, Here you go: http://jsbin.com/ugifab/edit#javascript,html,live
Thankyou so much 🙂 you are a star 🙂
James
Can you show how to I would configure a Sonic element using into a id=”mycanvas using
…
var canvas = document.getElementById(‘mycanvas’);
var ctx = canvas.getContext(‘2d’);
….
code
Thanks.
I will send a link to its final use.