chart-bar.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. (function(){
  2. "use strict";
  3. var root = this,
  4. Chart = root.Chart,
  5. helpers = Chart.helpers;
  6. var defaultConfig = {
  7. //Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
  8. scaleBeginAtZero : true,
  9. //Boolean - Whether grid lines are shown across the chart
  10. scaleShowGridLines : true,
  11. //String - Colour of the grid lines
  12. scaleGridLineColor : "rgba(0,0,0,.05)",
  13. //Number - Width of the grid lines
  14. scaleGridLineWidth : 1,
  15. //Boolean - If there is a stroke on each bar
  16. barShowStroke : true,
  17. //Number - Pixel width of the bar stroke
  18. barStrokeWidth : 2,
  19. //Number - Spacing between each of the X value sets
  20. barValueSpacing : 5,
  21. //Number - Spacing between data sets within X values
  22. barDatasetSpacing : 1,
  23. //String - A legend template
  24. legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].fillColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
  25. };
  26. Chart.Type.extend({
  27. name: "Bar",
  28. defaults : defaultConfig,
  29. initialize: function(data){
  30. //Expose options as a scope variable here so we can access it in the ScaleClass
  31. var options = this.options;
  32. this.ScaleClass = Chart.Scale.extend({
  33. offsetGridLines : true,
  34. calculateBarX : function(datasetCount, datasetIndex, barIndex){
  35. //Reusable method for calculating the xPosition of a given bar based on datasetIndex & width of the bar
  36. var xWidth = this.calculateBaseWidth(),
  37. xAbsolute = this.calculateX(barIndex) - (xWidth/2),
  38. barWidth = this.calculateBarWidth(datasetCount);
  39. return xAbsolute + (barWidth * datasetIndex) + (datasetIndex * options.barDatasetSpacing) + barWidth/2;
  40. },
  41. calculateBaseWidth : function(){
  42. return (this.calculateX(1) - this.calculateX(0)) - (2*options.barValueSpacing);
  43. },
  44. calculateBarWidth : function(datasetCount){
  45. //The padding between datasets is to the right of each bar, providing that there are more than 1 dataset
  46. var baseWidth = this.calculateBaseWidth() - ((datasetCount - 1) * options.barDatasetSpacing);
  47. return (baseWidth / datasetCount);
  48. }
  49. });
  50. this.datasets = [];
  51. //Set up tooltip events on the chart
  52. if (this.options.showTooltips){
  53. helpers.bindEvents(this, this.options.tooltipEvents, function(evt){
  54. var activeBars = (evt.type !== 'mouseout') ? this.getBarsAtEvent(evt) : [];
  55. this.eachBars(function(bar){
  56. bar.restore(['fillColor', 'strokeColor']);
  57. });
  58. helpers.each(activeBars, function(activeBar){
  59. activeBar.fillColor = activeBar.highlightFill;
  60. activeBar.strokeColor = activeBar.highlightStroke;
  61. });
  62. this.showTooltip(activeBars);
  63. });
  64. }
  65. //Declare the extension of the default point, to cater for the options passed in to the constructor
  66. this.BarClass = Chart.Rectangle.extend({
  67. strokeWidth : this.options.barStrokeWidth,
  68. showStroke : this.options.barShowStroke,
  69. ctx : this.chart.ctx
  70. });
  71. //Iterate through each of the datasets, and build this into a property of the chart
  72. helpers.each(data.datasets,function(dataset,datasetIndex){
  73. var datasetObject = {
  74. label : dataset.label || null,
  75. fillColor : dataset.fillColor,
  76. strokeColor : dataset.strokeColor,
  77. bars : []
  78. };
  79. this.datasets.push(datasetObject);
  80. helpers.each(dataset.data,function(dataPoint,index){
  81. //Add a new point for each piece of data, passing any required data to draw.
  82. datasetObject.bars.push(new this.BarClass({
  83. value : dataPoint,
  84. label : data.labels[index],
  85. datasetLabel: dataset.label,
  86. strokeColor : dataset.strokeColor,
  87. fillColor : dataset.fillColor,
  88. highlightFill : dataset.highlightFill || dataset.fillColor,
  89. highlightStroke : dataset.highlightStroke || dataset.strokeColor
  90. }));
  91. },this);
  92. },this);
  93. this.buildScale(data.labels);
  94. this.BarClass.prototype.base = this.scale.endPoint;
  95. this.eachBars(function(bar, index, datasetIndex){
  96. helpers.extend(bar, {
  97. width : this.scale.calculateBarWidth(this.datasets.length),
  98. x: this.scale.calculateBarX(this.datasets.length, datasetIndex, index),
  99. y: this.scale.endPoint
  100. });
  101. bar.save();
  102. }, this);
  103. this.render();
  104. },
  105. update : function(){
  106. this.scale.update();
  107. // Reset any highlight colours before updating.
  108. helpers.each(this.activeElements, function(activeElement){
  109. activeElement.restore(['fillColor', 'strokeColor']);
  110. });
  111. this.eachBars(function(bar){
  112. bar.save();
  113. });
  114. this.render();
  115. },
  116. eachBars : function(callback){
  117. helpers.each(this.datasets,function(dataset, datasetIndex){
  118. helpers.each(dataset.bars, callback, this, datasetIndex);
  119. },this);
  120. },
  121. getBarsAtEvent : function(e){
  122. var barsArray = [],
  123. eventPosition = helpers.getRelativePosition(e),
  124. datasetIterator = function(dataset){
  125. barsArray.push(dataset.bars[barIndex]);
  126. },
  127. barIndex;
  128. for (var datasetIndex = 0; datasetIndex < this.datasets.length; datasetIndex++) {
  129. for (barIndex = 0; barIndex < this.datasets[datasetIndex].bars.length; barIndex++) {
  130. if (this.datasets[datasetIndex].bars[barIndex].inRange(eventPosition.x,eventPosition.y)){
  131. helpers.each(this.datasets, datasetIterator);
  132. return barsArray;
  133. }
  134. }
  135. }
  136. return barsArray;
  137. },
  138. buildScale : function(labels){
  139. var self = this;
  140. var dataTotal = function(){
  141. var values = [];
  142. self.eachBars(function(bar){
  143. values.push(bar.value);
  144. });
  145. return values;
  146. };
  147. var scaleOptions = {
  148. templateString : this.options.scaleLabel,
  149. height : this.chart.height,
  150. width : this.chart.width,
  151. ctx : this.chart.ctx,
  152. textColor : this.options.scaleFontColor,
  153. fontSize : this.options.scaleFontSize,
  154. fontStyle : this.options.scaleFontStyle,
  155. fontFamily : this.options.scaleFontFamily,
  156. valuesCount : labels.length,
  157. beginAtZero : this.options.scaleBeginAtZero,
  158. integersOnly : this.options.scaleIntegersOnly,
  159. calculateYRange: function(currentHeight){
  160. var updatedRanges = helpers.calculateScaleRange(
  161. dataTotal(),
  162. currentHeight,
  163. this.fontSize,
  164. this.beginAtZero,
  165. this.integersOnly
  166. );
  167. helpers.extend(this, updatedRanges);
  168. },
  169. xLabels : labels,
  170. font : helpers.fontString(this.options.scaleFontSize, this.options.scaleFontStyle, this.options.scaleFontFamily),
  171. lineWidth : this.options.scaleLineWidth,
  172. lineColor : this.options.scaleLineColor,
  173. gridLineWidth : (this.options.scaleShowGridLines) ? this.options.scaleGridLineWidth : 0,
  174. gridLineColor : (this.options.scaleShowGridLines) ? this.options.scaleGridLineColor : "rgba(0,0,0,0)",
  175. padding : (this.options.showScale) ? 0 : (this.options.barShowStroke) ? this.options.barStrokeWidth : 0,
  176. showLabels : this.options.scaleShowLabels,
  177. display : this.options.showScale
  178. };
  179. if (this.options.scaleOverride){
  180. helpers.extend(scaleOptions, {
  181. calculateYRange: helpers.noop,
  182. steps: this.options.scaleSteps,
  183. stepValue: this.options.scaleStepWidth,
  184. min: this.options.scaleStartValue,
  185. max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth)
  186. });
  187. }
  188. this.scale = new this.ScaleClass(scaleOptions);
  189. },
  190. addData : function(valuesArray,label){
  191. //Map the values array for each of the datasets
  192. helpers.each(valuesArray,function(value,datasetIndex){
  193. //Add a new point for each piece of data, passing any required data to draw.
  194. this.datasets[datasetIndex].bars.push(new this.BarClass({
  195. value : value,
  196. label : label,
  197. x: this.scale.calculateBarX(this.datasets.length, datasetIndex, this.scale.valuesCount+1),
  198. y: this.scale.endPoint,
  199. width : this.scale.calculateBarWidth(this.datasets.length),
  200. base : this.scale.endPoint,
  201. strokeColor : this.datasets[datasetIndex].strokeColor,
  202. fillColor : this.datasets[datasetIndex].fillColor
  203. }));
  204. },this);
  205. this.scale.addXLabel(label);
  206. //Then re-render the chart.
  207. this.update();
  208. },
  209. removeData : function(){
  210. this.scale.removeXLabel();
  211. //Then re-render the chart.
  212. helpers.each(this.datasets,function(dataset){
  213. dataset.bars.shift();
  214. },this);
  215. this.update();
  216. },
  217. reflow : function(){
  218. helpers.extend(this.BarClass.prototype,{
  219. y: this.scale.endPoint,
  220. base : this.scale.endPoint
  221. });
  222. var newScaleProps = helpers.extend({
  223. height : this.chart.height,
  224. width : this.chart.width
  225. });
  226. this.scale.update(newScaleProps);
  227. },
  228. draw : function(ease){
  229. var easingDecimal = ease || 1;
  230. this.clear();
  231. var ctx = this.chart.ctx;
  232. this.scale.draw(easingDecimal);
  233. //Draw all the bars for each dataset
  234. helpers.each(this.datasets,function(dataset,datasetIndex){
  235. helpers.each(dataset.bars,function(bar,index){
  236. if (bar.hasValue()){
  237. bar.base = this.scale.endPoint;
  238. //Transition then draw
  239. bar.transition({
  240. x : this.scale.calculateBarX(this.datasets.length, datasetIndex, index),
  241. y : this.scale.calculateY(bar.value),
  242. width : this.scale.calculateBarWidth(this.datasets.length)
  243. }, easingDecimal).draw();
  244. }
  245. },this);
  246. },this);
  247. }
  248. });
  249. }).call(this);