/**
* Pie charts
*/
$.fn.sparkline.pie = pie = createClass($.fn.sparkline._base, {
type: 'pie',
init: function (el, values, options, width, height) {
var total = 0, i;
pie._super.init.call(this, el, values, options, width, height);
this.shapes = {}; // map shape ids to value offsets
this.valueShapes = {}; // maps value offsets to shape ids
this.values = values = $.map(values, Number);
if (options.get('width') === 'auto') {
this.width = this.height;
}
if (values.length > 0) {
for (i = values.length; i--;) {
total += values[i];
}
}
this.total = total;
this.initTarget();
this.radius = Math.floor(Math.min(this.canvasWidth, this.canvasHeight) / 2);
},
getRegion: function (el, x, y) {
var shapeid = this.target.getShapeAt(el, x, y);
return (shapeid !== undefined && this.shapes[shapeid] !== undefined) ? this.shapes[shapeid] : undefined;
},
getCurrentRegionFields: function () {
var currentRegion = this.currentRegion;
return {
isNull: this.values[currentRegion] === undefined,
value: this.values[currentRegion],
percent: this.values[currentRegion] / this.total * 100,
color: this.options.get('sliceColors')[currentRegion % this.options.get('sliceColors').length],
offset: currentRegion
};
},
changeHighlight: function (highlight) {
var currentRegion = this.currentRegion,
newslice = this.renderSlice(currentRegion, highlight),
shapeid = this.valueShapes[currentRegion];
delete this.shapes[shapeid];
this.target.replaceWithShape(shapeid, newslice);
this.valueShapes[currentRegion] = newslice.id;
this.shapes[newslice.id] = currentRegion;
},
renderSlice: function (valuenum, highlight) {
var target = this.target,
options = this.options,
radius = this.radius,
borderWidth = options.get('borderWidth'),
offset = options.get('offset'),
circle = 2 * Math.PI,
values = this.values,
total = this.total,
next = offset ? (2*Math.PI)*(offset/360) : 0,
start, end, i, vlen, color;
vlen = values.length;
for (i = 0; i < vlen; i++) {
start = next;
end = next;
if (total > 0) { // avoid divide by zero
end = next + (circle * (values[i] / total));
}
if (valuenum === i) {
color = options.get('sliceColors')[i % options.get('sliceColors').length];
if (highlight) {
color = this.calcHighlightColor(color, options);
}
return target.drawPieSlice(radius, radius, radius - borderWidth, start, end, undefined, color);
}
next = end;
}
},
render: function () {
var target = this.target,
values = this.values,
options = this.options,
radius = this.radius,
borderWidth = options.get('borderWidth'),
shape, i;
if (!pie._super.render.call(this)) {
return;
}
if (borderWidth) {
target.drawCircle(radius, radius, Math.floor(radius - (borderWidth / 2)),
options.get('borderColor'), undefined, borderWidth).append();
}
for (i = values.length; i--;) {
if (values[i]) { // don't render zero values
shape = this.renderSlice(i).append();
this.valueShapes[i] = shape.id; // store just the shapeid
this.shapes[shape.id] = i;
}
}
target.render();
}
});
|