Skip to content

Instantly share code, notes, and snippets.

@brennen
Created April 9, 2013 17:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brennen/5347518 to your computer and use it in GitHub Desktop.
Save brennen/5347518 to your computer and use it in GitHub Desktop.
(function( $ ){
var methods = {
init : function (options) {
},
render : function (target, data, labels, color) {
if (! (target && target.getContext))
return;
var context = target.getContext('2d');
context.strokeStyle = color;
context.font = 'Arial';
context.lineJoin = 'round';
context.textAlign = "center";
// our target canvas's size
var height = target.height;
var width = target.width;
var gridlines = 5; // TODO: there should be a way to automate this
var max = d3.max(data);
var barwidth = width / data.length; // how far apart should bars be?
var maxbarheight = height - 12;
var gridspace = Math.round(data.length / gridlines);
var scale = max / maxbarheight;
for (var i = 0; i < data.length; i++) {
var x = i * barwidth;
// gridlines & labels
if ((i % gridspace == 0) && (i > 0) && ((width - x) > 20)) {
context.fillStyle = 'lightgray';
context.fillRect(x, 12, 1, maxbarheight); // leave room at top for labels
context.fillText(labels[i], x, 10); // add label
}
context.fillStyle = color;
context.beginPath();
context.moveTo(x, height);
context.lineTo(x, height - (data[i] / scale));
context.lineTo(x + barwidth, height - (data[i] / scale));
context.lineTo(x + barwidth, height);
context.fill();
//context.stroke();
context.closePath();
}
}
};
// dispatch method calls like $(this).transmogrifier("isDirty") to
// the methods defined above:
$.fn.bpbarchart = function( method ) {
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.transmogrifier' );
}
};
})( jQuery );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment