Welcome to the adventure

Plotr (Javascript Graphing) for Mootools

Sunday June 10, 2007

Plotr is a Javascript toolkit for drawing arbitrary graphs. It does this by using the <canvas> tag, which allows you to draw rich graphics on the client. It’s supported by everyone except Internet Explorer. You can get around that by emulating canvas using IE’s VML rendering support (thanks Google!).

So, this library is great, but it’s written for Prototype. I needed it for a project using Mootools, so I wrote a small wrapper around some Prototype functions that allows you to drop in the Plotr release into your project without modifying it one bit, making it easy to update to new versions. This is doable because Mootools and Prototype are very similar: they each aim to do the least surprising thing, which tends to lead to similar APIs. And because the biggest Prototype-only feature — its extensive functionality for enumerable objects — has already been ported to Mootools by Bas Wenneker, the same author who wrote Plotr. Excellent.

So here’s what my wrapper around Prototype; it works against Mootools 1.0 and 1.1. In fact this probably will be enough to get most javascripts written for Prototype working on Mootools.

plotrmootoolssupport.js

/*
 * Supplements Mootools with some Prototype functions required by Plotr
 *
 *  (c) 2007 Phil Crosby <phil .crosby@gmail.com>
 */

Prototype={};
Class.create=function(){
	return new Class({});
};
Element.setStyle=function(){
	var e = $(arguments[0]);
	var a = arguments[1];
	// Prototype allows you to pass in many style declarations at once. Mootools
	// has a separate API for this
	if (typeof a=="object")
		e.setStyles(a);
	else
		e.setStyle(a);
};

Array.prototype.flatten=function(){
    return this.inject([], function(array, value) {
      return array.concat(value && value.constructor == Array ?
        value.flatten() : [value]);
    });
};

Number.prototype.toColorPart= function() {
    var digits = this.toString(16);
    if (this < 16) return '0' + digits;
    return digits;
};

Throw in the EnumArray.js file from Bas Wenneker and you’re ready to go. Include the files in this order in your project:

mootools.js
plotrMootoolsSupport.js
EnumArray.js
plotr.js

Give your users a break by combining the last 3 javascripts into one file (in that order). Thanks Bas for the great library.