Skip to content

Instantly share code, notes, and snippets.

@xriss
Last active Dec 16, 2015
Embed
What would you like to do?
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