Send to Kindle

Sunday, May 16, 2010

Animating with Raphaël.js

‹prev | My Chain | next›

Tonight, I continue my exploration of raphaël.js. Last night, I was able to get the basic canvas in place and hook in an event listener into my (fab) game. At that point, I realized that it was going to require some refactoring of the player animation to work with raphaël.js. Now I start that refactoring.

The difference between my <canvas> based animation and the way that raphaël animates is that my <canvas> code only watches/reports as the player itself moves. Raphaël's animateAlong() moves items about on its "paper", then reports on locations. I had hoped my code would prove decoupled enough that I could change only the Room or only the Player. Sadly, both will require changes.

First up, I re-arrange the player list and room so that player list knows about the room, not the other way around:
    var room = new Room($("#room-container")[0]);
player_list = new PlayerList(me, room);
The room no longer needs to watch the players—now the players will have to watch what happens in the room. After updating the constructors of each, I provide a means for the player list to tell each Player about the raphaël.js drawing element:
Player.prototype.attach_drawable = function(drawable) {
this.drawable = drawable;
This "drawable" element in the room comes from the circle object drawn by the Room:
Room.prototype.draw_player = function(player, color) {
var c =, player.x, 3);
c.attr({fill: color, opacity: 0.5});
return c;
(It is the player list's job to attach the two).

With that, I can call the raphaël.js animateAlong() method with an SVG path element to animate the motion of the player in the room:
Player.prototype.walk_to = function(x, y) {
var self = this;
var p = "M"+ this.x + " " + this.y +
"L" + x + " " + y;
this.drawable.animateAlong(p, 3000)
With that, I can actually animate my players again:


Nice! That was a bit easier than working with <canvas> (which probably helped overcoming some problems I might have encountered). Unfortunately, I do run into one of the problems I had already solved in my <canvas> code—clicking a new destination before the animation has completed fouls up the walk (animations combine).

I am unsure if that can be resolved easily in raphaël.js. I will investigate tomorrow.

Day #105

1 comment: