Skip to content

Instantly share code, notes, and snippets.

@atbradley
Created June 15, 2015 12:27
Show Gist options
  • Save atbradley/a03941977435a1adfc55 to your computer and use it in GitHub Desktop.
Save atbradley/a03941977435a1adfc55 to your computer and use it in GitHub Desktop.
Generate sparklines based on 'data-data' attributes of canvases.
//NOTE: Depends on paper.js.
if ('undefined' == typeof unset) function isset(x) { return !('undefined' == typeof x) }
if ( !isset(ifunset) ) function ifunset(x, def) { return ('undefined' == typeof x) ? def : x; }
//These are defaults; config variables can be set before loading this script.
var LOGGING = ifunset(LOGGING, false);
var CANVAS_SELECTOR = ifunset(CANVAS_SELECTOR, 'canvas.sparkler');
var XMARGIN = ifunset(XMARGIN, 2);
var YMARGIN = ifunset(YMARGIN, 2);
var LINE_COLOR = ifunset(LINE_COLOR, '#666666');
var DOT_COLOR = ifunset(LINE_COLOR, 'yellow');
var logger = LOGGING ? console : {log: function() {}};
$().ready(function() {
$(CANVAS_SELECTOR).each(function(i, el) {
atb_sparkler(el);
});
});
atb_sparkler = function(canv) {
jcanv = $(canv);
canv = jcanv.get(0); //Make sure canv is a basic DOM object.
data = JSON.parse(jcanv.attr('data-data'));
max = Math.max.apply(null, data);
min = Math.min.apply(null, data);
dist = max-min;
var step = (jcanv.innerWidth()-XMARGIN) / (data.length-1);
var ht = jcanv.innerHeight() - (YMARGIN*2);
logger.log(data, max, min, step);
paper.setup(canv);
var spark = new paper.Path();
for ( i=0; i<data.length; i++ ) {
thisy = ht-((data[i]-min)/dist*ht) + YMARGIN;
spark.add([i*step, thisy]);
logger.log( data[i], max, ht, i*step, thisy );
}
spark.strokeColor = LINE_COLOR;
//var dirc = new paper.Path.Circle([i*step, thisy], 10);dirc.fillColor='red';
endpoint = new paper.Point([(i-1)*step, thisy]);
var dot = new paper.Path.Circle(endpoint, 2);
dot.fillColor='red';
logger.log(dot, dot.position.x, dot.position.y, [i*step, thisy]);
paper.view.draw();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment