Saturday, May 15, 2010

Getting Started with Raphaël.js

‹prev | My Chain | next›

Tonight, I will explore drawing my game with the raphaël.js javascript framework. I have no interest in cross-browser support (Webkit and Firefox are sufficient), but I would like to see if drawing things are easier with it and maybe a little less CPU intensive.

So I remove my <canvas> tag, replacing it with a container for my raphaël.js canvas:
   <div id="room-container"></div>
...and pass this into my Room constructor:
    new Room($("#room-container")[0], player_list);
After updating my constructor to expect the container rather than a <canvas> element, my draw routine starts in with the raphaël.js:
Room.prototype.draw = function() {

this.paper = Raphael(this.container, 500, 500);
this.paper.rect(0, 0, 500, 500, 10).attr({fill: "#fff", stroke: "none"});

// calls to draw the players
This initializes a raphaël element, clears it, then fills it in with white. Simple enough. Drawing players with raphaël is also fairly straight forward:
Room.prototype.draw_player = function(player, color) {
var c =, player.x, 3);
c.attr({fill: color, opacity: 0.5});
I just borrow some of the sample code from the very excellent documentation for drawing circles. I now have a nicely rendered room with very little effort:

Unfortunately, now I run into problems. I move players about by clicking on the room and having them follow the click. The problem here is trying to figure out where to attach that click event. When I was using a straight <canvas> element, I could attach my click handler directly to it. That does not work with raphaël, nor can I attach the handler to the "paper"'s node.

In the end I am forced to attach the handler to the containing <div>:
Room.prototype.init_events = function() {
var self = this;
$(this.container).click(function(evt) {
var decorated_event = self.decorate_event(evt);
function(subscriber) { subscriber.notify(decorated_event); }
Although the event is not listening on the real target, it seems to be close enough. My player is again notified of the event and sends movement information to the fab.js backend once more.

I stop here for the night. Tomorrow I will pick back up with animating my players inside raphaël. That seem relatively easy to do, but it will require a fair bit of rejiggering of responsibilities in my code so far.

Day #104

No comments:

Post a Comment