Wednesday, July 21, 2010

My Very Own Raphaël.js Plugin

‹prev | My Chain | next›

Today, I would like to convert my work of the past few days into a raphaël.js function. As of yesterday, I have a set of functions that can take an array of SVG objects (manually copied from Inkscape) and cycle through them as the objects move about the screen:



I would like to add onto Raphael so that I can do something like:
var standing = { ... };
var walking = { ... };

var frames = paper.svg_frames(standing, walking);

// Animate by cycling through the frames as the
// object moves to x-y 100,100
frames.translate(100, 100, 5*1000);
I spend a good deal of time re-working code from the past couple of days into this structure:
Raphael.fn.svg_frames = function() {
var paper = this;

var frames = {
list: [],

add: function() { ... },

draw_part: function(attrs) { ... },

draw_object: function(attr_list) { ... },

attrs_from_string: function(str) { ... },

show_frame: function(frame) { ... },

hide_frame: function(frame) { ... },

translate: function(x, y, seconds) { ... },

toggle_frames: function(count) { ... },

translate_object: function(obj, x, y, seconds) { ... }

};

frames.add(arguments);
frames.show_frame(frames.list[0]);

return frames;
}
As the raphaël documentations suggests, I add my new svg_frames function onto Raphael.fn. That will allow it to be called from an instance of raphaël paper. Since I am converting from a purely functional approach to a frames object, I spend most of my time removing the list argument that many functions took (it is now an attribute of frames) and adding var self = this as appropriate:
    toggle_frames: function(count) {
var self = this;
var frames = this.list;

if (!count) count=0;

// toggle code here

if (count < 10) {
setTimeout(function(){self.toggle_frames(count+1)}, 500);
}
}
Aside from minor tweaks along those lines, I have very little else needed to change. Just like that, I can move my animations around the raphaël paper by calling a function directly on the paper:
var standing = { ... };
var walking = { ... };

var paper = Raphael("container", 500, 500);

paper
.svg_frames(standing, walking);
.translate(100, 100, 5*1000);
I still have some refactoring to do in the code itself, but I am pleased that it was so easy to get this done today.


Day #171

No comments:

Post a Comment