Skip to content

Instantly share code, notes, and snippets.

@xriss
Last active December 16, 2015 14:00
Show Gist options
  • Save xriss/640126818e3320733622 to your computer and use it in GitHub Desktop.
Save xriss/640126818e3320733622 to your computer and use it in GitHub Desktop.
chartjs v2 - bartop controller that displays value at top of bar chart using y axis formating
(function() {
"use strict";
var root = this,
Chart = root.Chart,
helpers = Chart.helpers;
Chart.defaults.bartop = helpers.extendDeep({},Chart.defaults.bar);
Chart.controllers.bartop = function(chart, datasetIndex) {
this.initialize.call(this, chart, datasetIndex);
};
helpers.extend(Chart.controllers.bartop.prototype,Chart.controllers.bar.prototype,{
draw: function(ease) {
var easingDecimal = ease || 1;
helpers.each(this.getDataset().metaData, function(rectangle, index) {
rectangle.transition(easingDecimal).draw();
}, this);
var ctx=this.chart.chart.ctx;
var ticks=this.chart.scales["y-axis-0"]; // is this a safe way to get the yaxis?
var options=ticks.options;
var labelFont = helpers.fontString(options.ticks.fontSize, options.ticks.fontStyle, options.ticks.fontFamily);
ctx.font = labelFont;
ctx.fillStyle = options.ticks.fontColor;
helpers.each(this.getDataset().metaData, function(rectangle, index) {
var value=this.getDataset().data[index];
var vm = rectangle._view;
var top = vm.base - (vm.base - vm.y);
var text=options.ticks.callback(value, index, ticks);
ctx.save();
ctx.font = labelFont;
ctx.textAlign = "center";
ctx.textBaseline = "bottom" ;
ctx.fillText(text, vm.x, top);
ctx.restore();
}, this);
},
});
}).call(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment