What is Snap.svg?
Snap is designed to be a modern replacement for the likes of Raphael. Instead of focusing on compatibility with the older browsers like Internet Explorer 6, Snap instead drops support for older browsers in favor of a more complete SVG feature set.
A nondescript mustachioed figure
I’ll show how I made this basic interactive. (If you want to know how I made the source SVG file, let me know, I’ll do up a tutorial for that if there’s interest)
While this interactive doesn’t have a whole lot of real-world practicality, it does have the core functionality you’d need when making your own interactive website elements.
- Loading an external SVG file
- Element selection
- Setting element attributes
- Binding user events
- Basic animation
Here we just load the required Snap library and create a new Snap object. I am also loading jQuery, however this isn’t required, I am just lazy and am using it for brevity.
Snap.load(FILENAME, CALLBACK) loads the
FILENAME and passes it to the
CALLBACK function as a Snap object. We then use the Snap selector
select(SELECTOR) to grab the group with the
s1.append(layer0); adds the mario group to the
<SVG> tag in the DOM. We get the following.
Please select player
We use the
selectAll() function on our loaded layer to find all the
RECT objects (all the “pixels” in the source SVG are
RECT nodes.) We can set some attributes on these nodes using the
Here we are also setting some attributes (
origX/Y) that we’ll use when we apply animation.
It’s dangerous to go alone
style="" attributes for that node. Try clicking on the pixels below.
Da da daa da daa DA! (huh?!?)
Here we’ve set some variables,
animation_time. We also set some attributes
modX/Y which are the X and Y co-ords of where we want each pixel to animate to on
origX/Y are the original X and Y co-ords. We store this so that we have the values to animate backwards after
animate() takes an object of attributes we want to animate, the length of the animation and finally the easing method. Snap uses mina, and there are half a dozen or so easing methods. They all have their time and place.
Once we run all this we get our original Mario interactive.
Our princess is in another castle
As stated earlier, this interactive doesn’t really have a lot of practicality, but hopefully from the info I’ve provided you will be able to imagine useful and unique interactive elements to embed into your websites. The examples provided should illustrate to you the basics of what you can do with Snap.svg.
If you have any questions, or want me to cover any particular section in depth. Leave a comment below and I’ll do my best.
You can download the sourcecode for the interactive here example.tar.gz