選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

3477 行
107KB

  1. /*!
  2. * Chart.js
  3. * http://chartjs.org/
  4. * Version: 1.0.2
  5. *
  6. * Copyright 2015 Nick Downie
  7. * Released under the MIT license
  8. * https://github.com/nnnick/Chart.js/blob/master/LICENSE.md
  9. */
  10. (function(){
  11. "use strict";
  12. //Declare root variable - window in the browser, global on the server
  13. var root = this,
  14. previous = root.Chart;
  15. //Occupy the global variable of Chart, and create a simple base class
  16. var Chart = function(context){
  17. var chart = this;
  18. this.canvas = context.canvas;
  19. this.ctx = context;
  20. //Variables global to the chart
  21. var computeDimension = function(element,dimension)
  22. {
  23. if (element['offset'+dimension])
  24. {
  25. return element['offset'+dimension];
  26. }
  27. else
  28. {
  29. return document.defaultView.getComputedStyle(element).getPropertyValue(dimension);
  30. }
  31. }
  32. var width = this.width = computeDimension(context.canvas,'Width');
  33. var height = this.height = computeDimension(context.canvas,'Height');
  34. // Firefox requires this to work correctly
  35. context.canvas.width = width;
  36. context.canvas.height = height;
  37. var width = this.width = context.canvas.width;
  38. var height = this.height = context.canvas.height;
  39. this.aspectRatio = this.width / this.height;
  40. //High pixel density displays - multiply the size of the canvas height/width by the device pixel ratio, then scale.
  41. helpers.retinaScale(this);
  42. return this;
  43. };
  44. //Globally expose the defaults to allow for user updating/changing
  45. Chart.defaults = {
  46. global: {
  47. // Boolean - Whether to animate the chart
  48. animation: true,
  49. // Number - Number of animation steps
  50. animationSteps: 60,
  51. // String - Animation easing effect
  52. animationEasing: "easeOutQuart",
  53. // Boolean - If we should show the scale at all
  54. showScale: true,
  55. // Boolean - If we want to override with a hard coded scale
  56. scaleOverride: false,
  57. // ** Required if scaleOverride is true **
  58. // Number - The number of steps in a hard coded scale
  59. scaleSteps: null,
  60. // Number - The value jump in the hard coded scale
  61. scaleStepWidth: null,
  62. // Number - The scale starting value
  63. scaleStartValue: null,
  64. // String - Colour of the scale line
  65. scaleLineColor: "rgba(0,0,0,.1)",
  66. // Number - Pixel width of the scale line
  67. scaleLineWidth: 1,
  68. // Boolean - Whether to show labels on the scale
  69. scaleShowLabels: true,
  70. // Interpolated JS string - can access value
  71. scaleLabel: "<%=value%>",
  72. // Boolean - Whether the scale should stick to integers, and not show any floats even if drawing space is there
  73. scaleIntegersOnly: true,
  74. // Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
  75. scaleBeginAtZero: false,
  76. // String - Scale label font declaration for the scale label
  77. scaleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
  78. // Number - Scale label font size in pixels
  79. scaleFontSize: 12,
  80. // String - Scale label font weight style
  81. scaleFontStyle: "normal",
  82. // String - Scale label font colour
  83. scaleFontColor: "#666",
  84. // Boolean - whether or not the chart should be responsive and resize when the browser does.
  85. responsive: false,
  86. // Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
  87. maintainAspectRatio: true,
  88. // Boolean - Determines whether to draw tooltips on the canvas or not - attaches events to touchmove & mousemove
  89. showTooltips: true,
  90. // Boolean - Determines whether to draw built-in tooltip or call custom tooltip function
  91. customTooltips: false,
  92. // Array - Array of string names to attach tooltip events
  93. tooltipEvents: ["mousemove", "touchstart", "touchmove", "mouseout"],
  94. // String - Tooltip background colour
  95. tooltipFillColor: "rgba(0,0,0,0.8)",
  96. // String - Tooltip label font declaration for the scale label
  97. tooltipFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
  98. // Number - Tooltip label font size in pixels
  99. tooltipFontSize: 14,
  100. // String - Tooltip font weight style
  101. tooltipFontStyle: "normal",
  102. // String - Tooltip label font colour
  103. tooltipFontColor: "#fff",
  104. // String - Tooltip title font declaration for the scale label
  105. tooltipTitleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
  106. // Number - Tooltip title font size in pixels
  107. tooltipTitleFontSize: 14,
  108. // String - Tooltip title font weight style
  109. tooltipTitleFontStyle: "bold",
  110. // String - Tooltip title font colour
  111. tooltipTitleFontColor: "#fff",
  112. // Number - pixel width of padding around tooltip text
  113. tooltipYPadding: 6,
  114. // Number - pixel width of padding around tooltip text
  115. tooltipXPadding: 6,
  116. // Number - Size of the caret on the tooltip
  117. tooltipCaretSize: 8,
  118. // Number - Pixel radius of the tooltip border
  119. tooltipCornerRadius: 6,
  120. // Number - Pixel offset from point x to tooltip edge
  121. tooltipXOffset: 10,
  122. // String - Template string for single tooltips
  123. tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>",
  124. // String - Template string for single tooltips
  125. multiTooltipTemplate: "<%= value %>",
  126. // String - Colour behind the legend colour block
  127. multiTooltipKeyBackground: '#fff',
  128. // Function - Will fire on animation progression.
  129. onAnimationProgress: function(){},
  130. // Function - Will fire on animation completion.
  131. onAnimationComplete: function(){}
  132. }
  133. };
  134. //Create a dictionary of chart types, to allow for extension of existing types
  135. Chart.types = {};
  136. //Global Chart helpers object for utility methods and classes
  137. var helpers = Chart.helpers = {};
  138. //-- Basic js utility methods
  139. var each = helpers.each = function(loopable,callback,self){
  140. var additionalArgs = Array.prototype.slice.call(arguments, 3);
  141. // Check to see if null or undefined firstly.
  142. if (loopable){
  143. if (loopable.length === +loopable.length){
  144. var i;
  145. for (i=0; i<loopable.length; i++){
  146. callback.apply(self,[loopable[i], i].concat(additionalArgs));
  147. }
  148. }
  149. else{
  150. for (var item in loopable){
  151. callback.apply(self,[loopable[item],item].concat(additionalArgs));
  152. }
  153. }
  154. }
  155. },
  156. clone = helpers.clone = function(obj){
  157. var objClone = {};
  158. each(obj,function(value,key){
  159. if (obj.hasOwnProperty(key)) objClone[key] = value;
  160. });
  161. return objClone;
  162. },
  163. extend = helpers.extend = function(base){
  164. each(Array.prototype.slice.call(arguments,1), function(extensionObject) {
  165. each(extensionObject,function(value,key){
  166. if (extensionObject.hasOwnProperty(key)) base[key] = value;
  167. });
  168. });
  169. return base;
  170. },
  171. merge = helpers.merge = function(base,master){
  172. //Merge properties in left object over to a shallow clone of object right.
  173. var args = Array.prototype.slice.call(arguments,0);
  174. args.unshift({});
  175. return extend.apply(null, args);
  176. },
  177. indexOf = helpers.indexOf = function(arrayToSearch, item){
  178. if (Array.prototype.indexOf) {
  179. return arrayToSearch.indexOf(item);
  180. }
  181. else{
  182. for (var i = 0; i < arrayToSearch.length; i++) {
  183. if (arrayToSearch[i] === item) return i;
  184. }
  185. return -1;
  186. }
  187. },
  188. where = helpers.where = function(collection, filterCallback){
  189. var filtered = [];
  190. helpers.each(collection, function(item){
  191. if (filterCallback(item)){
  192. filtered.push(item);
  193. }
  194. });
  195. return filtered;
  196. },
  197. findNextWhere = helpers.findNextWhere = function(arrayToSearch, filterCallback, startIndex){
  198. // Default to start of the array
  199. if (!startIndex){
  200. startIndex = -1;
  201. }
  202. for (var i = startIndex + 1; i < arrayToSearch.length; i++) {
  203. var currentItem = arrayToSearch[i];
  204. if (filterCallback(currentItem)){
  205. return currentItem;
  206. }
  207. }
  208. },
  209. findPreviousWhere = helpers.findPreviousWhere = function(arrayToSearch, filterCallback, startIndex){
  210. // Default to end of the array
  211. if (!startIndex){
  212. startIndex = arrayToSearch.length;
  213. }
  214. for (var i = startIndex - 1; i >= 0; i--) {
  215. var currentItem = arrayToSearch[i];
  216. if (filterCallback(currentItem)){
  217. return currentItem;
  218. }
  219. }
  220. },
  221. inherits = helpers.inherits = function(extensions){
  222. //Basic javascript inheritance based on the model created in Backbone.js
  223. var parent = this;
  224. var ChartElement = (extensions && extensions.hasOwnProperty("constructor")) ? extensions.constructor : function(){ return parent.apply(this, arguments); };
  225. var Surrogate = function(){ this.constructor = ChartElement;};
  226. Surrogate.prototype = parent.prototype;
  227. ChartElement.prototype = new Surrogate();
  228. ChartElement.extend = inherits;
  229. if (extensions) extend(ChartElement.prototype, extensions);
  230. ChartElement.__super__ = parent.prototype;
  231. return ChartElement;
  232. },
  233. noop = helpers.noop = function(){},
  234. uid = helpers.uid = (function(){
  235. var id=0;
  236. return function(){
  237. return "chart-" + id++;
  238. };
  239. })(),
  240. warn = helpers.warn = function(str){
  241. //Method for warning of errors
  242. if (window.console && typeof window.console.warn == "function") console.warn(str);
  243. },
  244. amd = helpers.amd = (typeof define == 'function' && define.amd),
  245. //-- Math methods
  246. isNumber = helpers.isNumber = function(n){
  247. return !isNaN(parseFloat(n)) && isFinite(n);
  248. },
  249. max = helpers.max = function(array){
  250. return Math.max.apply( Math, array );
  251. },
  252. min = helpers.min = function(array){
  253. return Math.min.apply( Math, array );
  254. },
  255. cap = helpers.cap = function(valueToCap,maxValue,minValue){
  256. if(isNumber(maxValue)) {
  257. if( valueToCap > maxValue ) {
  258. return maxValue;
  259. }
  260. }
  261. else if(isNumber(minValue)){
  262. if ( valueToCap < minValue ){
  263. return minValue;
  264. }
  265. }
  266. return valueToCap;
  267. },
  268. getDecimalPlaces = helpers.getDecimalPlaces = function(num){
  269. if (num%1!==0 && isNumber(num)){
  270. return num.toString().split(".")[1].length;
  271. }
  272. else {
  273. return 0;
  274. }
  275. },
  276. toRadians = helpers.radians = function(degrees){
  277. return degrees * (Math.PI/180);
  278. },
  279. // Gets the angle from vertical upright to the point about a centre.
  280. getAngleFromPoint = helpers.getAngleFromPoint = function(centrePoint, anglePoint){
  281. var distanceFromXCenter = anglePoint.x - centrePoint.x,
  282. distanceFromYCenter = anglePoint.y - centrePoint.y,
  283. radialDistanceFromCenter = Math.sqrt( distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
  284. var angle = Math.PI * 2 + Math.atan2(distanceFromYCenter, distanceFromXCenter);
  285. //If the segment is in the top left quadrant, we need to add another rotation to the angle
  286. if (distanceFromXCenter < 0 && distanceFromYCenter < 0){
  287. angle += Math.PI*2;
  288. }
  289. return {
  290. angle: angle,
  291. distance: radialDistanceFromCenter
  292. };
  293. },
  294. aliasPixel = helpers.aliasPixel = function(pixelWidth){
  295. return (pixelWidth % 2 === 0) ? 0 : 0.5;
  296. },
  297. splineCurve = helpers.splineCurve = function(FirstPoint,MiddlePoint,AfterPoint,t){
  298. //Props to Rob Spencer at scaled innovation for his post on splining between points
  299. //http://scaledinnovation.com/analytics/splines/aboutSplines.html
  300. var d01=Math.sqrt(Math.pow(MiddlePoint.x-FirstPoint.x,2)+Math.pow(MiddlePoint.y-FirstPoint.y,2)),
  301. d12=Math.sqrt(Math.pow(AfterPoint.x-MiddlePoint.x,2)+Math.pow(AfterPoint.y-MiddlePoint.y,2)),
  302. fa=t*d01/(d01+d12),// scaling factor for triangle Ta
  303. fb=t*d12/(d01+d12);
  304. return {
  305. inner : {
  306. x : MiddlePoint.x-fa*(AfterPoint.x-FirstPoint.x),
  307. y : MiddlePoint.y-fa*(AfterPoint.y-FirstPoint.y)
  308. },
  309. outer : {
  310. x: MiddlePoint.x+fb*(AfterPoint.x-FirstPoint.x),
  311. y : MiddlePoint.y+fb*(AfterPoint.y-FirstPoint.y)
  312. }
  313. };
  314. },
  315. calculateOrderOfMagnitude = helpers.calculateOrderOfMagnitude = function(val){
  316. return Math.floor(Math.log(val) / Math.LN10);
  317. },
  318. calculateScaleRange = helpers.calculateScaleRange = function(valuesArray, drawingSize, textSize, startFromZero, integersOnly){
  319. //Set a minimum step of two - a point at the top of the graph, and a point at the base
  320. var minSteps = 2,
  321. maxSteps = Math.floor(drawingSize/(textSize * 1.5)),
  322. skipFitting = (minSteps >= maxSteps);
  323. var maxValue = max(valuesArray),
  324. minValue = min(valuesArray);
  325. // We need some degree of seperation here to calculate the scales if all the values are the same
  326. // Adding/minusing 0.5 will give us a range of 1.
  327. if (maxValue === minValue){
  328. maxValue += 0.5;
  329. // So we don't end up with a graph with a negative start value if we've said always start from zero
  330. if (minValue >= 0.5 && !startFromZero){
  331. minValue -= 0.5;
  332. }
  333. else{
  334. // Make up a whole number above the values
  335. maxValue += 0.5;
  336. }
  337. }
  338. var valueRange = Math.abs(maxValue - minValue),
  339. rangeOrderOfMagnitude = calculateOrderOfMagnitude(valueRange),
  340. graphMax = Math.ceil(maxValue / (1 * Math.pow(10, rangeOrderOfMagnitude))) * Math.pow(10, rangeOrderOfMagnitude),
  341. graphMin = (startFromZero) ? 0 : Math.floor(minValue / (1 * Math.pow(10, rangeOrderOfMagnitude))) * Math.pow(10, rangeOrderOfMagnitude),
  342. graphRange = graphMax - graphMin,
  343. stepValue = Math.pow(10, rangeOrderOfMagnitude),
  344. numberOfSteps = Math.round(graphRange / stepValue);
  345. //If we have more space on the graph we'll use it to give more definition to the data
  346. while((numberOfSteps > maxSteps || (numberOfSteps * 2) < maxSteps) && !skipFitting) {
  347. if(numberOfSteps > maxSteps){
  348. stepValue *=2;
  349. numberOfSteps = Math.round(graphRange/stepValue);
  350. // Don't ever deal with a decimal number of steps - cancel fitting and just use the minimum number of steps.
  351. if (numberOfSteps % 1 !== 0){
  352. skipFitting = true;
  353. }
  354. }
  355. //We can fit in double the amount of scale points on the scale
  356. else{
  357. //If user has declared ints only, and the step value isn't a decimal
  358. if (integersOnly && rangeOrderOfMagnitude >= 0){
  359. //If the user has said integers only, we need to check that making the scale more granular wouldn't make it a float
  360. if(stepValue/2 % 1 === 0){
  361. stepValue /=2;
  362. numberOfSteps = Math.round(graphRange/stepValue);
  363. }
  364. //If it would make it a float break out of the loop
  365. else{
  366. break;
  367. }
  368. }
  369. //If the scale doesn't have to be an int, make the scale more granular anyway.
  370. else{
  371. stepValue /=2;
  372. numberOfSteps = Math.round(graphRange/stepValue);
  373. }
  374. }
  375. }
  376. if (skipFitting){
  377. numberOfSteps = minSteps;
  378. stepValue = graphRange / numberOfSteps;
  379. }
  380. return {
  381. steps : numberOfSteps,
  382. stepValue : stepValue,
  383. min : graphMin,
  384. max : graphMin + (numberOfSteps * stepValue)
  385. };
  386. },
  387. /* jshint ignore:start */
  388. // Blows up jshint errors based on the new Function constructor
  389. //Templating methods
  390. //Javascript micro templating by John Resig - source at http://ejohn.org/blog/javascript-micro-templating/
  391. template = helpers.template = function(templateString, valuesObject){
  392. // If templateString is function rather than string-template - call the function for valuesObject
  393. if(templateString instanceof Function){
  394. return templateString(valuesObject);
  395. }
  396. var cache = {};
  397. function tmpl(str, data){
  398. // Figure out if we're getting a template, or if we need to
  399. // load the template - and be sure to cache the result.
  400. var fn = !/\W/.test(str) ?
  401. cache[str] = cache[str] :
  402. // Generate a reusable function that will serve as a template
  403. // generator (and which will be cached).
  404. new Function("obj",
  405. "var p=[],print=function(){p.push.apply(p,arguments);};" +
  406. // Introduce the data as local variables using with(){}
  407. "with(obj){p.push('" +
  408. // Convert the template into pure JavaScript
  409. str
  410. .replace(/[\r\t\n]/g, " ")
  411. .split("<%").join("\t")
  412. .replace(/((^|%>)[^\t]*)'/g, "$1\r")
  413. .replace(/\t=(.*?)%>/g, "',$1,'")
  414. .split("\t").join("');")
  415. .split("%>").join("p.push('")
  416. .split("\r").join("\\'") +
  417. "');}return p.join('');"
  418. );
  419. // Provide some basic currying to the user
  420. return data ? fn( data ) : fn;
  421. }
  422. return tmpl(templateString,valuesObject);
  423. },
  424. /* jshint ignore:end */
  425. generateLabels = helpers.generateLabels = function(templateString,numberOfSteps,graphMin,stepValue){
  426. var labelsArray = new Array(numberOfSteps);
  427. if (labelTemplateString){
  428. each(labelsArray,function(val,index){
  429. labelsArray[index] = template(templateString,{value: (graphMin + (stepValue*(index+1)))});
  430. });
  431. }
  432. return labelsArray;
  433. },
  434. //--Animation methods
  435. //Easing functions adapted from Robert Penner's easing equations
  436. //http://www.robertpenner.com/easing/
  437. easingEffects = helpers.easingEffects = {
  438. linear: function (t) {
  439. return t;
  440. },
  441. easeInQuad: function (t) {
  442. return t * t;
  443. },
  444. easeOutQuad: function (t) {
  445. return -1 * t * (t - 2);
  446. },
  447. easeInOutQuad: function (t) {
  448. if ((t /= 1 / 2) < 1) return 1 / 2 * t * t;
  449. return -1 / 2 * ((--t) * (t - 2) - 1);
  450. },
  451. easeInCubic: function (t) {
  452. return t * t * t;
  453. },
  454. easeOutCubic: function (t) {
  455. return 1 * ((t = t / 1 - 1) * t * t + 1);
  456. },
  457. easeInOutCubic: function (t) {
  458. if ((t /= 1 / 2) < 1) return 1 / 2 * t * t * t;
  459. return 1 / 2 * ((t -= 2) * t * t + 2);
  460. },
  461. easeInQuart: function (t) {
  462. return t * t * t * t;
  463. },
  464. easeOutQuart: function (t) {
  465. return -1 * ((t = t / 1 - 1) * t * t * t - 1);
  466. },
  467. easeInOutQuart: function (t) {
  468. if ((t /= 1 / 2) < 1) return 1 / 2 * t * t * t * t;
  469. return -1 / 2 * ((t -= 2) * t * t * t - 2);
  470. },
  471. easeInQuint: function (t) {
  472. return 1 * (t /= 1) * t * t * t * t;
  473. },
  474. easeOutQuint: function (t) {
  475. return 1 * ((t = t / 1 - 1) * t * t * t * t + 1);
  476. },
  477. easeInOutQuint: function (t) {
  478. if ((t /= 1 / 2) < 1) return 1 / 2 * t * t * t * t * t;
  479. return 1 / 2 * ((t -= 2) * t * t * t * t + 2);
  480. },
  481. easeInSine: function (t) {
  482. return -1 * Math.cos(t / 1 * (Math.PI / 2)) + 1;
  483. },
  484. easeOutSine: function (t) {
  485. return 1 * Math.sin(t / 1 * (Math.PI / 2));
  486. },
  487. easeInOutSine: function (t) {
  488. return -1 / 2 * (Math.cos(Math.PI * t / 1) - 1);
  489. },
  490. easeInExpo: function (t) {
  491. return (t === 0) ? 1 : 1 * Math.pow(2, 10 * (t / 1 - 1));
  492. },
  493. easeOutExpo: function (t) {
  494. return (t === 1) ? 1 : 1 * (-Math.pow(2, -10 * t / 1) + 1);
  495. },
  496. easeInOutExpo: function (t) {
  497. if (t === 0) return 0;
  498. if (t === 1) return 1;
  499. if ((t /= 1 / 2) < 1) return 1 / 2 * Math.pow(2, 10 * (t - 1));
  500. return 1 / 2 * (-Math.pow(2, -10 * --t) + 2);
  501. },
  502. easeInCirc: function (t) {
  503. if (t >= 1) return t;
  504. return -1 * (Math.sqrt(1 - (t /= 1) * t) - 1);
  505. },
  506. easeOutCirc: function (t) {
  507. return 1 * Math.sqrt(1 - (t = t / 1 - 1) * t);
  508. },
  509. easeInOutCirc: function (t) {
  510. if ((t /= 1 / 2) < 1) return -1 / 2 * (Math.sqrt(1 - t * t) - 1);
  511. return 1 / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1);
  512. },
  513. easeInElastic: function (t) {
  514. var s = 1.70158;
  515. var p = 0;
  516. var a = 1;
  517. if (t === 0) return 0;
  518. if ((t /= 1) == 1) return 1;
  519. if (!p) p = 1 * 0.3;
  520. if (a < Math.abs(1)) {
  521. a = 1;
  522. s = p / 4;
  523. } else s = p / (2 * Math.PI) * Math.asin(1 / a);
  524. return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p));
  525. },
  526. easeOutElastic: function (t) {
  527. var s = 1.70158;
  528. var p = 0;
  529. var a = 1;
  530. if (t === 0) return 0;
  531. if ((t /= 1) == 1) return 1;
  532. if (!p) p = 1 * 0.3;
  533. if (a < Math.abs(1)) {
  534. a = 1;
  535. s = p / 4;
  536. } else s = p / (2 * Math.PI) * Math.asin(1 / a);
  537. return a * Math.pow(2, -10 * t) * Math.sin((t * 1 - s) * (2 * Math.PI) / p) + 1;
  538. },
  539. easeInOutElastic: function (t) {
  540. var s = 1.70158;
  541. var p = 0;
  542. var a = 1;
  543. if (t === 0) return 0;
  544. if ((t /= 1 / 2) == 2) return 1;
  545. if (!p) p = 1 * (0.3 * 1.5);
  546. if (a < Math.abs(1)) {
  547. a = 1;
  548. s = p / 4;
  549. } else s = p / (2 * Math.PI) * Math.asin(1 / a);
  550. if (t < 1) return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p));
  551. return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p) * 0.5 + 1;
  552. },
  553. easeInBack: function (t) {
  554. var s = 1.70158;
  555. return 1 * (t /= 1) * t * ((s + 1) * t - s);
  556. },
  557. easeOutBack: function (t) {
  558. var s = 1.70158;
  559. return 1 * ((t = t / 1 - 1) * t * ((s + 1) * t + s) + 1);
  560. },
  561. easeInOutBack: function (t) {
  562. var s = 1.70158;
  563. if ((t /= 1 / 2) < 1) return 1 / 2 * (t * t * (((s *= (1.525)) + 1) * t - s));
  564. return 1 / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
  565. },
  566. easeInBounce: function (t) {
  567. return 1 - easingEffects.easeOutBounce(1 - t);
  568. },
  569. easeOutBounce: function (t) {
  570. if ((t /= 1) < (1 / 2.75)) {
  571. return 1 * (7.5625 * t * t);
  572. } else if (t < (2 / 2.75)) {
  573. return 1 * (7.5625 * (t -= (1.5 / 2.75)) * t + 0.75);
  574. } else if (t < (2.5 / 2.75)) {
  575. return 1 * (7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375);
  576. } else {
  577. return 1 * (7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375);
  578. }
  579. },
  580. easeInOutBounce: function (t) {
  581. if (t < 1 / 2) return easingEffects.easeInBounce(t * 2) * 0.5;
  582. return easingEffects.easeOutBounce(t * 2 - 1) * 0.5 + 1 * 0.5;
  583. }
  584. },
  585. //Request animation polyfill - http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
  586. requestAnimFrame = helpers.requestAnimFrame = (function(){
  587. return window.requestAnimationFrame ||
  588. window.webkitRequestAnimationFrame ||
  589. window.mozRequestAnimationFrame ||
  590. window.oRequestAnimationFrame ||
  591. window.msRequestAnimationFrame ||
  592. function(callback) {
  593. return window.setTimeout(callback, 1000 / 60);
  594. };
  595. })(),
  596. cancelAnimFrame = helpers.cancelAnimFrame = (function(){
  597. return window.cancelAnimationFrame ||
  598. window.webkitCancelAnimationFrame ||
  599. window.mozCancelAnimationFrame ||
  600. window.oCancelAnimationFrame ||
  601. window.msCancelAnimationFrame ||
  602. function(callback) {
  603. return window.clearTimeout(callback, 1000 / 60);
  604. };
  605. })(),
  606. animationLoop = helpers.animationLoop = function(callback,totalSteps,easingString,onProgress,onComplete,chartInstance){
  607. var currentStep = 0,
  608. easingFunction = easingEffects[easingString] || easingEffects.linear;
  609. var animationFrame = function(){
  610. currentStep++;
  611. var stepDecimal = currentStep/totalSteps;
  612. var easeDecimal = easingFunction(stepDecimal);
  613. callback.call(chartInstance,easeDecimal,stepDecimal, currentStep);
  614. onProgress.call(chartInstance,easeDecimal,stepDecimal);
  615. if (currentStep < totalSteps){
  616. chartInstance.animationFrame = requestAnimFrame(animationFrame);
  617. } else{
  618. onComplete.apply(chartInstance);
  619. }
  620. };
  621. requestAnimFrame(animationFrame);
  622. },
  623. //-- DOM methods
  624. getRelativePosition = helpers.getRelativePosition = function(evt){
  625. var mouseX, mouseY;
  626. var e = evt.originalEvent || evt,
  627. canvas = evt.currentTarget || evt.srcElement,
  628. boundingRect = canvas.getBoundingClientRect();
  629. if (e.touches){
  630. mouseX = e.touches[0].clientX - boundingRect.left;
  631. mouseY = e.touches[0].clientY - boundingRect.top;
  632. }
  633. else{
  634. mouseX = e.clientX - boundingRect.left;
  635. mouseY = e.clientY - boundingRect.top;
  636. }
  637. return {
  638. x : mouseX,
  639. y : mouseY
  640. };
  641. },
  642. addEvent = helpers.addEvent = function(node,eventType,method){
  643. if (node.addEventListener){
  644. node.addEventListener(eventType,method);
  645. } else if (node.attachEvent){
  646. node.attachEvent("on"+eventType, method);
  647. } else {
  648. node["on"+eventType] = method;
  649. }
  650. },
  651. removeEvent = helpers.removeEvent = function(node, eventType, handler){
  652. if (node.removeEventListener){
  653. node.removeEventListener(eventType, handler, false);
  654. } else if (node.detachEvent){
  655. node.detachEvent("on"+eventType,handler);
  656. } else{
  657. node["on" + eventType] = noop;
  658. }
  659. },
  660. bindEvents = helpers.bindEvents = function(chartInstance, arrayOfEvents, handler){
  661. // Create the events object if it's not already present
  662. if (!chartInstance.events) chartInstance.events = {};
  663. each(arrayOfEvents,function(eventName){
  664. chartInstance.events[eventName] = function(){
  665. handler.apply(chartInstance, arguments);
  666. };
  667. addEvent(chartInstance.chart.canvas,eventName,chartInstance.events[eventName]);
  668. });
  669. },
  670. unbindEvents = helpers.unbindEvents = function (chartInstance, arrayOfEvents) {
  671. each(arrayOfEvents, function(handler,eventName){
  672. removeEvent(chartInstance.chart.canvas, eventName, handler);
  673. });
  674. },
  675. getMaximumWidth = helpers.getMaximumWidth = function(domNode){
  676. var container = domNode.parentNode;
  677. // TODO = check cross browser stuff with this.
  678. return container.clientWidth;
  679. },
  680. getMaximumHeight = helpers.getMaximumHeight = function(domNode){
  681. var container = domNode.parentNode;
  682. // TODO = check cross browser stuff with this.
  683. return container.clientHeight;
  684. },
  685. getMaximumSize = helpers.getMaximumSize = helpers.getMaximumWidth, // legacy support
  686. retinaScale = helpers.retinaScale = function(chart){
  687. var ctx = chart.ctx,
  688. width = chart.canvas.width,
  689. height = chart.canvas.height;
  690. if (window.devicePixelRatio) {
  691. ctx.canvas.style.width = width + "px";
  692. ctx.canvas.style.height = height + "px";
  693. ctx.canvas.height = height * window.devicePixelRatio;
  694. ctx.canvas.width = width * window.devicePixelRatio;
  695. ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
  696. }
  697. },
  698. //-- Canvas methods
  699. clear = helpers.clear = function(chart){
  700. chart.ctx.clearRect(0,0,chart.width,chart.height);
  701. },
  702. fontString = helpers.fontString = function(pixelSize,fontStyle,fontFamily){
  703. return fontStyle + " " + pixelSize+"px " + fontFamily;
  704. },
  705. longestText = helpers.longestText = function(ctx,font,arrayOfStrings){
  706. ctx.font = font;
  707. var longest = 0;
  708. each(arrayOfStrings,function(string){
  709. var textWidth = ctx.measureText(string).width;
  710. longest = (textWidth > longest) ? textWidth : longest;
  711. });
  712. return longest;
  713. },
  714. drawRoundedRectangle = helpers.drawRoundedRectangle = function(ctx,x,y,width,height,radius){
  715. ctx.beginPath();
  716. ctx.moveTo(x + radius, y);
  717. ctx.lineTo(x + width - radius, y);
  718. ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
  719. ctx.lineTo(x + width, y + height - radius);
  720. ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
  721. ctx.lineTo(x + radius, y + height);
  722. ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
  723. ctx.lineTo(x, y + radius);
  724. ctx.quadraticCurveTo(x, y, x + radius, y);
  725. ctx.closePath();
  726. };
  727. //Store a reference to each instance - allowing us to globally resize chart instances on window resize.
  728. //Destroy method on the chart will remove the instance of the chart from this reference.
  729. Chart.instances = {};
  730. Chart.Type = function(data,options,chart){
  731. this.options = options;
  732. this.chart = chart;
  733. this.id = uid();
  734. //Add the chart instance to the global namespace
  735. Chart.instances[this.id] = this;
  736. // Initialize is always called when a chart type is created
  737. // By default it is a no op, but it should be extended
  738. if (options.responsive){
  739. this.resize();
  740. }
  741. this.initialize.call(this,data);
  742. };
  743. //Core methods that'll be a part of every chart type
  744. extend(Chart.Type.prototype,{
  745. initialize : function(){return this;},
  746. clear : function(){
  747. clear(this.chart);
  748. return this;
  749. },
  750. stop : function(){
  751. // Stops any current animation loop occuring
  752. cancelAnimFrame(this.animationFrame);
  753. return this;
  754. },
  755. resize : function(callback){
  756. this.stop();
  757. var canvas = this.chart.canvas,
  758. newWidth = getMaximumWidth(this.chart.canvas),
  759. newHeight = this.options.maintainAspectRatio ? newWidth / this.chart.aspectRatio : getMaximumHeight(this.chart.canvas);
  760. canvas.width = this.chart.width = newWidth;
  761. canvas.height = this.chart.height = newHeight;
  762. retinaScale(this.chart);
  763. if (typeof callback === "function"){
  764. callback.apply(this, Array.prototype.slice.call(arguments, 1));
  765. }
  766. return this;
  767. },
  768. reflow : noop,
  769. render : function(reflow){
  770. if (reflow){
  771. this.reflow();
  772. }
  773. if (this.options.animation && !reflow){
  774. helpers.animationLoop(
  775. this.draw,
  776. this.options.animationSteps,
  777. this.options.animationEasing,
  778. this.options.onAnimationProgress,
  779. this.options.onAnimationComplete,
  780. this
  781. );
  782. }
  783. else{
  784. this.draw();
  785. this.options.onAnimationComplete.call(this);
  786. }
  787. return this;
  788. },
  789. generateLegend : function(){
  790. return template(this.options.legendTemplate,this);
  791. },
  792. destroy : function(){
  793. this.clear();
  794. unbindEvents(this, this.events);
  795. var canvas = this.chart.canvas;
  796. // Reset canvas height/width attributes starts a fresh with the canvas context
  797. canvas.width = this.chart.width;
  798. canvas.height = this.chart.height;
  799. // < IE9 doesn't support removeProperty
  800. if (canvas.style.removeProperty) {
  801. canvas.style.removeProperty('width');
  802. canvas.style.removeProperty('height');
  803. } else {
  804. canvas.style.removeAttribute('width');
  805. canvas.style.removeAttribute('height');
  806. }
  807. delete Chart.instances[this.id];
  808. },
  809. showTooltip : function(ChartElements, forceRedraw){
  810. // Only redraw the chart if we've actually changed what we're hovering on.
  811. if (typeof this.activeElements === 'undefined') this.activeElements = [];
  812. var isChanged = (function(Elements){
  813. var changed = false;
  814. if (Elements.length !== this.activeElements.length){
  815. changed = true;
  816. return changed;
  817. }
  818. each(Elements, function(element, index){
  819. if (element !== this.activeElements[index]){
  820. changed = true;
  821. }
  822. }, this);
  823. return changed;
  824. }).call(this, ChartElements);
  825. if (!isChanged && !forceRedraw){
  826. return;
  827. }
  828. else{
  829. this.activeElements = ChartElements;
  830. }
  831. this.draw();
  832. if(this.options.customTooltips){
  833. this.options.customTooltips(false);
  834. }
  835. if (ChartElements.length > 0){
  836. // If we have multiple datasets, show a MultiTooltip for all of the data points at that index
  837. if (this.datasets && this.datasets.length > 1) {
  838. var dataArray,
  839. dataIndex;
  840. for (var i = this.datasets.length - 1; i >= 0; i--) {
  841. dataArray = this.datasets[i].points || this.datasets[i].bars || this.datasets[i].segments;
  842. dataIndex = indexOf(dataArray, ChartElements[0]);
  843. if (dataIndex !== -1){
  844. break;
  845. }
  846. }
  847. var tooltipLabels = [],
  848. tooltipColors = [],
  849. medianPosition = (function(index) {
  850. // Get all the points at that particular index
  851. var Elements = [],
  852. dataCollection,
  853. xPositions = [],
  854. yPositions = [],
  855. xMax,
  856. yMax,
  857. xMin,
  858. yMin;
  859. helpers.each(this.datasets, function(dataset){
  860. dataCollection = dataset.points || dataset.bars || dataset.segments;
  861. if (dataCollection[dataIndex] && dataCollection[dataIndex].hasValue()){
  862. Elements.push(dataCollection[dataIndex]);
  863. }
  864. });
  865. helpers.each(Elements, function(element) {
  866. xPositions.push(element.x);
  867. yPositions.push(element.y);
  868. //Include any colour information about the element
  869. tooltipLabels.push(helpers.template(this.options.multiTooltipTemplate, element));
  870. tooltipColors.push({
  871. fill: element._saved.fillColor || element.fillColor,
  872. stroke: element._saved.strokeColor || element.strokeColor
  873. });
  874. }, this);
  875. yMin = min(yPositions);
  876. yMax = max(yPositions);
  877. xMin = min(xPositions);
  878. xMax = max(xPositions);
  879. return {
  880. x: (xMin > this.chart.width/2) ? xMin : xMax,
  881. y: (yMin + yMax)/2
  882. };
  883. }).call(this, dataIndex);
  884. new Chart.MultiTooltip({
  885. x: medianPosition.x,
  886. y: medianPosition.y,
  887. xPadding: this.options.tooltipXPadding,
  888. yPadding: this.options.tooltipYPadding,
  889. xOffset: this.options.tooltipXOffset,
  890. fillColor: this.options.tooltipFillColor,
  891. textColor: this.options.tooltipFontColor,
  892. fontFamily: this.options.tooltipFontFamily,
  893. fontStyle: this.options.tooltipFontStyle,
  894. fontSize: this.options.tooltipFontSize,
  895. titleTextColor: this.options.tooltipTitleFontColor,
  896. titleFontFamily: this.options.tooltipTitleFontFamily,
  897. titleFontStyle: this.options.tooltipTitleFontStyle,
  898. titleFontSize: this.options.tooltipTitleFontSize,
  899. cornerRadius: this.options.tooltipCornerRadius,
  900. labels: tooltipLabels,
  901. legendColors: tooltipColors,
  902. legendColorBackground : this.options.multiTooltipKeyBackground,
  903. title: ChartElements[0].label,
  904. chart: this.chart,
  905. ctx: this.chart.ctx,
  906. custom: this.options.customTooltips
  907. }).draw();
  908. } else {
  909. each(ChartElements, function(Element) {
  910. var tooltipPosition = Element.tooltipPosition();
  911. new Chart.Tooltip({
  912. x: Math.round(tooltipPosition.x),
  913. y: Math.round(tooltipPosition.y),
  914. xPadding: this.options.tooltipXPadding,
  915. yPadding: this.options.tooltipYPadding,
  916. fillColor: this.options.tooltipFillColor,
  917. textColor: this.options.tooltipFontColor,
  918. fontFamily: this.options.tooltipFontFamily,
  919. fontStyle: this.options.tooltipFontStyle,
  920. fontSize: this.options.tooltipFontSize,
  921. caretHeight: this.options.tooltipCaretSize,
  922. cornerRadius: this.options.tooltipCornerRadius,
  923. text: template(this.options.tooltipTemplate, Element),
  924. chart: this.chart,
  925. custom: this.options.customTooltips
  926. }).draw();
  927. }, this);
  928. }
  929. }
  930. return this;
  931. },
  932. toBase64Image : function(){
  933. return this.chart.canvas.toDataURL.apply(this.chart.canvas, arguments);
  934. }
  935. });
  936. Chart.Type.extend = function(extensions){
  937. var parent = this;
  938. var ChartType = function(){
  939. return parent.apply(this,arguments);
  940. };
  941. //Copy the prototype object of the this class
  942. ChartType.prototype = clone(parent.prototype);
  943. //Now overwrite some of the properties in the base class with the new extensions
  944. extend(ChartType.prototype, extensions);
  945. ChartType.extend = Chart.Type.extend;
  946. if (extensions.name || parent.prototype.name){
  947. var chartName = extensions.name || parent.prototype.name;
  948. //Assign any potential default values of the new chart type
  949. //If none are defined, we'll use a clone of the chart type this is being extended from.
  950. //I.e. if we extend a line chart, we'll use the defaults from the line chart if our new chart
  951. //doesn't define some defaults of their own.
  952. var baseDefaults = (Chart.defaults[parent.prototype.name]) ? clone(Chart.defaults[parent.prototype.name]) : {};
  953. Chart.defaults[chartName] = extend(baseDefaults,extensions.defaults);
  954. Chart.types[chartName] = ChartType;
  955. //Register this new chart type in the Chart prototype
  956. Chart.prototype[chartName] = function(data,options){
  957. var config = merge(Chart.defaults.global, Chart.defaults[chartName], options || {});
  958. return new ChartType(data,config,this);
  959. };
  960. } else{
  961. warn("Name not provided for this chart, so it hasn't been registered");
  962. }
  963. return parent;
  964. };
  965. Chart.Element = function(configuration){
  966. extend(this,configuration);
  967. this.initialize.apply(this,arguments);
  968. this.save();
  969. };
  970. extend(Chart.Element.prototype,{
  971. initialize : function(){},
  972. restore : function(props){
  973. if (!props){
  974. extend(this,this._saved);
  975. } else {
  976. each(props,function(key){
  977. this[key] = this._saved[key];
  978. },this);
  979. }
  980. return this;
  981. },
  982. save : function(){
  983. this._saved = clone(this);
  984. delete this._saved._saved;
  985. return this;
  986. },
  987. update : function(newProps){
  988. each(newProps,function(value,key){
  989. this._saved[key] = this[key];
  990. this[key] = value;
  991. },this);
  992. return this;
  993. },
  994. transition : function(props,ease){
  995. each(props,function(value,key){
  996. this[key] = ((value - this._saved[key]) * ease) + this._saved[key];
  997. },this);
  998. return this;
  999. },
  1000. tooltipPosition : function(){
  1001. return {
  1002. x : this.x,
  1003. y : this.y
  1004. };
  1005. },
  1006. hasValue: function(){
  1007. return isNumber(this.value);
  1008. }
  1009. });
  1010. Chart.Element.extend = inherits;
  1011. Chart.Point = Chart.Element.extend({
  1012. display: true,
  1013. inRange: function(chartX,chartY){
  1014. var hitDetectionRange = this.hitDetectionRadius + this.radius;
  1015. return ((Math.pow(chartX-this.x, 2)+Math.pow(chartY-this.y, 2)) < Math.pow(hitDetectionRange,2));
  1016. },
  1017. draw : function(){
  1018. if (this.display){
  1019. var ctx = this.ctx;
  1020. ctx.beginPath();
  1021. ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2);
  1022. ctx.closePath();
  1023. ctx.strokeStyle = this.strokeColor;
  1024. ctx.lineWidth = this.strokeWidth;
  1025. ctx.fillStyle = this.fillColor;
  1026. ctx.fill();
  1027. ctx.stroke();
  1028. }
  1029. //Quick debug for bezier curve splining
  1030. //Highlights control points and the line between them.
  1031. //Handy for dev - stripped in the min version.
  1032. // ctx.save();
  1033. // ctx.fillStyle = "black";
  1034. // ctx.strokeStyle = "black"
  1035. // ctx.beginPath();
  1036. // ctx.arc(this.controlPoints.inner.x,this.controlPoints.inner.y, 2, 0, Math.PI*2);
  1037. // ctx.fill();
  1038. // ctx.beginPath();
  1039. // ctx.arc(this.controlPoints.outer.x,this.controlPoints.outer.y, 2, 0, Math.PI*2);
  1040. // ctx.fill();
  1041. // ctx.moveTo(this.controlPoints.inner.x,this.controlPoints.inner.y);
  1042. // ctx.lineTo(this.x, this.y);
  1043. // ctx.lineTo(this.controlPoints.outer.x,this.controlPoints.outer.y);
  1044. // ctx.stroke();
  1045. // ctx.restore();
  1046. }
  1047. });
  1048. Chart.Arc = Chart.Element.extend({
  1049. inRange : function(chartX,chartY){
  1050. var pointRelativePosition = helpers.getAngleFromPoint(this, {
  1051. x: chartX,
  1052. y: chartY
  1053. });
  1054. //Check if within the range of the open/close angle
  1055. var betweenAngles = (pointRelativePosition.angle >= this.startAngle && pointRelativePosition.angle <= this.endAngle),
  1056. withinRadius = (pointRelativePosition.distance >= this.innerRadius && pointRelativePosition.distance <= this.outerRadius);
  1057. return (betweenAngles && withinRadius);
  1058. //Ensure within the outside of the arc centre, but inside arc outer
  1059. },
  1060. tooltipPosition : function(){
  1061. var centreAngle = this.startAngle + ((this.endAngle - this.startAngle) / 2),
  1062. rangeFromCentre = (this.outerRadius - this.innerRadius) / 2 + this.innerRadius;
  1063. return {
  1064. x : this.x + (Math.cos(centreAngle) * rangeFromCentre),
  1065. y : this.y + (Math.sin(centreAngle) * rangeFromCentre)
  1066. };
  1067. },
  1068. draw : function(animationPercent){
  1069. var easingDecimal = animationPercent || 1;
  1070. var ctx = this.ctx;
  1071. ctx.beginPath();
  1072. ctx.arc(this.x, this.y, this.outerRadius, this.startAngle, this.endAngle);
  1073. ctx.arc(this.x, this.y, this.innerRadius, this.endAngle, this.startAngle, true);
  1074. ctx.closePath();
  1075. ctx.strokeStyle = this.strokeColor;
  1076. ctx.lineWidth = this.strokeWidth;
  1077. ctx.fillStyle = this.fillColor;
  1078. ctx.fill();
  1079. ctx.lineJoin = 'bevel';
  1080. if (this.showStroke){
  1081. ctx.stroke();
  1082. }
  1083. }
  1084. });
  1085. Chart.Rectangle = Chart.Element.extend({
  1086. draw : function(){
  1087. var ctx = this.ctx,
  1088. halfWidth = this.width/2,
  1089. leftX = this.x - halfWidth,
  1090. rightX = this.x + halfWidth,
  1091. top = this.base - (this.base - this.y),
  1092. halfStroke = this.strokeWidth / 2;
  1093. // Canvas doesn't allow us to stroke inside the width so we can
  1094. // adjust the sizes to fit if we're setting a stroke on the line
  1095. if (this.showStroke){
  1096. leftX += halfStroke;
  1097. rightX -= halfStroke;
  1098. top += halfStroke;
  1099. }
  1100. ctx.beginPath();
  1101. ctx.fillStyle = this.fillColor;
  1102. ctx.strokeStyle = this.strokeColor;
  1103. ctx.lineWidth = this.strokeWidth;
  1104. // It'd be nice to keep this class totally generic to any rectangle
  1105. // and simply specify which border to miss out.
  1106. ctx.moveTo(leftX, this.base);
  1107. ctx.lineTo(leftX, top);
  1108. ctx.lineTo(rightX, top);
  1109. ctx.lineTo(rightX, this.base);
  1110. ctx.fill();
  1111. if (this.showStroke){
  1112. ctx.stroke();
  1113. }
  1114. },
  1115. height : function(){
  1116. return this.base - this.y;
  1117. },
  1118. inRange : function(chartX,chartY){
  1119. return (chartX >= this.x - this.width/2 && chartX <= this.x + this.width/2) && (chartY >= this.y && chartY <= this.base);
  1120. }
  1121. });
  1122. Chart.Tooltip = Chart.Element.extend({
  1123. draw : function(){
  1124. var ctx = this.chart.ctx;
  1125. ctx.font = fontString(this.fontSize,this.fontStyle,this.fontFamily);
  1126. this.xAlign = "center";
  1127. this.yAlign = "above";
  1128. //Distance between the actual element.y position and the start of the tooltip caret
  1129. var caretPadding = this.caretPadding = 2;
  1130. var tooltipWidth = ctx.measureText(this.text).width + 2*this.xPadding,
  1131. tooltipRectHeight = this.fontSize + 2*this.yPadding,
  1132. tooltipHeight = tooltipRectHeight + this.caretHeight + caretPadding;
  1133. if (this.x + tooltipWidth/2 >this.chart.width){
  1134. this.xAlign = "left";
  1135. } else if (this.x - tooltipWidth/2 < 0){
  1136. this.xAlign = "right";
  1137. }
  1138. if (this.y - tooltipHeight < 0){
  1139. this.yAlign = "below";
  1140. }
  1141. var tooltipX = this.x - tooltipWidth/2,
  1142. tooltipY = this.y - tooltipHeight;
  1143. ctx.fillStyle = this.fillColor;
  1144. // Custom Tooltips
  1145. if(this.custom){
  1146. this.custom(this);
  1147. }
  1148. else{
  1149. switch(this.yAlign)
  1150. {
  1151. case "above":
  1152. //Draw a caret above the x/y
  1153. ctx.beginPath();
  1154. ctx.moveTo(this.x,this.y - caretPadding);
  1155. ctx.lineTo(this.x + this.caretHeight, this.y - (caretPadding + this.caretHeight));
  1156. ctx.lineTo(this.x - this.caretHeight, this.y - (caretPadding + this.caretHeight));
  1157. ctx.closePath();
  1158. ctx.fill();
  1159. break;
  1160. case "below":
  1161. tooltipY = this.y + caretPadding + this.caretHeight;
  1162. //Draw a caret below the x/y
  1163. ctx.beginPath();
  1164. ctx.moveTo(this.x, this.y + caretPadding);
  1165. ctx.lineTo(this.x + this.caretHeight, this.y + caretPadding + this.caretHeight);
  1166. ctx.lineTo(this.x - this.caretHeight, this.y + caretPadding + this.caretHeight);
  1167. ctx.closePath();
  1168. ctx.fill();
  1169. break;
  1170. }
  1171. switch(this.xAlign)
  1172. {
  1173. case "left":
  1174. tooltipX = this.x - tooltipWidth + (this.cornerRadius + this.caretHeight);
  1175. break;
  1176. case "right":
  1177. tooltipX = this.x - (this.cornerRadius + this.caretHeight);
  1178. break;
  1179. }
  1180. drawRoundedRectangle(ctx,tooltipX,tooltipY,tooltipWidth,tooltipRectHeight,this.cornerRadius);
  1181. ctx.fill();
  1182. ctx.fillStyle = this.textColor;
  1183. ctx.textAlign = "center";
  1184. ctx.textBaseline = "middle";
  1185. ctx.fillText(this.text, tooltipX + tooltipWidth/2, tooltipY + tooltipRectHeight/2);
  1186. }
  1187. }
  1188. });
  1189. Chart.MultiTooltip = Chart.Element.extend({
  1190. initialize : function(){
  1191. this.font = fontString(this.fontSize,this.fontStyle,this.fontFamily);
  1192. this.titleFont = fontString(this.titleFontSize,this.titleFontStyle,this.titleFontFamily);
  1193. this.height = (this.labels.length * this.fontSize) + ((this.labels.length-1) * (this.fontSize/2)) + (this.yPadding*2) + this.titleFontSize *1.5;
  1194. this.ctx.font = this.titleFont;
  1195. var titleWidth = this.ctx.measureText(this.title).width,
  1196. //Label has a legend square as well so account for this.
  1197. labelWidth = longestText(this.ctx,this.font,this.labels) + this.fontSize + 3,
  1198. longestTextWidth = max([labelWidth,titleWidth]);
  1199. this.width = longestTextWidth + (this.xPadding*2);
  1200. var halfHeight = this.height/2;
  1201. //Check to ensure the height will fit on the canvas
  1202. if (this.y - halfHeight < 0 ){
  1203. this.y = halfHeight;
  1204. } else if (this.y + halfHeight > this.chart.height){
  1205. this.y = this.chart.height - halfHeight;
  1206. }
  1207. //Decide whether to align left or right based on position on canvas
  1208. if (this.x > this.chart.width/2){
  1209. this.x -= this.xOffset + this.width;
  1210. } else {
  1211. this.x += this.xOffset;
  1212. }
  1213. },
  1214. getLineHeight : function(index){
  1215. var baseLineHeight = this.y - (this.height/2) + this.yPadding,
  1216. afterTitleIndex = index-1;
  1217. //If the index is zero, we're getting the title
  1218. if (index === 0){
  1219. return baseLineHeight + this.titleFontSize/2;
  1220. } else{
  1221. return baseLineHeight + ((this.fontSize*1.5*afterTitleIndex) + this.fontSize/2) + this.titleFontSize * 1.5;
  1222. }
  1223. },
  1224. draw : function(){
  1225. // Custom Tooltips
  1226. if(this.custom){
  1227. this.custom(this);
  1228. }
  1229. else{
  1230. drawRoundedRectangle(this.ctx,this.x,this.y - this.height/2,this.width,this.height,this.cornerRadius);
  1231. var ctx = this.ctx;
  1232. ctx.fillStyle = this.fillColor;
  1233. ctx.fill();
  1234. ctx.closePath();
  1235. ctx.textAlign = "left";
  1236. ctx.textBaseline = "middle";
  1237. ctx.fillStyle = this.titleTextColor;
  1238. ctx.font = this.titleFont;
  1239. ctx.fillText(this.title,this.x + this.xPadding, this.getLineHeight(0));
  1240. ctx.font = this.font;
  1241. helpers.each(this.labels,function(label,index){
  1242. ctx.fillStyle = this.textColor;
  1243. ctx.fillText(label,this.x + this.xPadding + this.fontSize + 3, this.getLineHeight(index + 1));
  1244. //A bit gnarly, but clearing this rectangle breaks when using explorercanvas (clears whole canvas)
  1245. //ctx.clearRect(this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize/2, this.fontSize, this.fontSize);
  1246. //Instead we'll make a white filled block to put the legendColour palette over.
  1247. ctx.fillStyle = this.legendColorBackground;
  1248. ctx.fillRect(this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize/2, this.fontSize, this.fontSize);
  1249. ctx.fillStyle = this.legendColors[index].fill;
  1250. ctx.fillRect(this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize/2, this.fontSize, this.fontSize);
  1251. },this);
  1252. }
  1253. }
  1254. });
  1255. Chart.Scale = Chart.Element.extend({
  1256. initialize : function(){
  1257. this.fit();
  1258. },
  1259. buildYLabels : function(){
  1260. this.yLabels = [];
  1261. var stepDecimalPlaces = getDecimalPlaces(this.stepValue);
  1262. for (var i=0; i<=this.steps; i++){
  1263. this.yLabels.push(template(this.templateString,{value:(this.min + (i * this.stepValue)).toFixed(stepDecimalPlaces)}));
  1264. }
  1265. this.yLabelWidth = (this.display && this.showLabels) ? longestText(this.ctx,this.font,this.yLabels) : 0;
  1266. },
  1267. addXLabel : function(label){
  1268. this.xLabels.push(label);
  1269. this.valuesCount++;
  1270. this.fit();
  1271. },
  1272. removeXLabel : function(){
  1273. this.xLabels.shift();
  1274. this.valuesCount--;
  1275. this.fit();
  1276. },
  1277. // Fitting loop to rotate x Labels and figure out what fits there, and also calculate how many Y steps to use
  1278. fit: function(){
  1279. // First we need the width of the yLabels, assuming the xLabels aren't rotated
  1280. // To do that we need the base line at the top and base of the chart, assuming there is no x label rotation
  1281. this.startPoint = (this.display) ? this.fontSize : 0;
  1282. this.endPoint = (this.display) ? this.height - (this.fontSize * 1.5) - 5 : this.height; // -5 to pad labels
  1283. // Apply padding settings to the start and end point.
  1284. this.startPoint += this.padding;
  1285. this.endPoint -= this.padding;
  1286. // Cache the starting height, so can determine if we need to recalculate the scale yAxis
  1287. var cachedHeight = this.endPoint - this.startPoint,
  1288. cachedYLabelWidth;
  1289. // Build the current yLabels so we have an idea of what size they'll be to start
  1290. /*
  1291. * This sets what is returned from calculateScaleRange as static properties of this class:
  1292. *
  1293. this.steps;
  1294. this.stepValue;
  1295. this.min;
  1296. this.max;
  1297. *
  1298. */
  1299. this.calculateYRange(cachedHeight);
  1300. // With these properties set we can now build the array of yLabels
  1301. // and also the width of the largest yLabel
  1302. this.buildYLabels();
  1303. this.calculateXLabelRotation();
  1304. while((cachedHeight > this.endPoint - this.startPoint)){
  1305. cachedHeight = this.endPoint - this.startPoint;
  1306. cachedYLabelWidth = this.yLabelWidth;
  1307. this.calculateYRange(cachedHeight);
  1308. this.buildYLabels();
  1309. // Only go through the xLabel loop again if the yLabel width has changed
  1310. if (cachedYLabelWidth < this.yLabelWidth){
  1311. this.calculateXLabelRotation();
  1312. }
  1313. }
  1314. },
  1315. calculateXLabelRotation : function(){
  1316. //Get the width of each grid by calculating the difference
  1317. //between x offsets between 0 and 1.
  1318. this.ctx.font = this.font;
  1319. var firstWidth = this.ctx.measureText(this.xLabels[0]).width,
  1320. lastWidth = this.ctx.measureText(this.xLabels[this.xLabels.length - 1]).width,
  1321. firstRotated,
  1322. lastRotated;
  1323. this.xScalePaddingRight = lastWidth/2 + 3;
  1324. this.xScalePaddingLeft = (firstWidth/2 > this.yLabelWidth + 10) ? firstWidth/2 : this.yLabelWidth + 10;
  1325. this.xLabelRotation = 0;
  1326. if (this.display){
  1327. var originalLabelWidth = longestText(this.ctx,this.font,this.xLabels),
  1328. cosRotation,
  1329. firstRotatedWidth;
  1330. this.xLabelWidth = originalLabelWidth;
  1331. //Allow 3 pixels x2 padding either side for label readability
  1332. var xGridWidth = Math.floor(this.calculateX(1) - this.calculateX(0)) - 6;
  1333. //Max label rotate should be 90 - also act as a loop counter
  1334. while ((this.xLabelWidth > xGridWidth && this.xLabelRotation === 0) || (this.xLabelWidth > xGridWidth && this.xLabelRotation <= 90 && this.xLabelRotation > 0)){
  1335. cosRotation = Math.cos(toRadians(this.xLabelRotation));
  1336. firstRotated = cosRotation * firstWidth;
  1337. lastRotated = cosRotation * lastWidth;
  1338. // We're right aligning the text now.
  1339. if (firstRotated + this.fontSize / 2 > this.yLabelWidth + 8){
  1340. this.xScalePaddingLeft = firstRotated + this.fontSize / 2;
  1341. }
  1342. this.xScalePaddingRight = this.fontSize/2;
  1343. this.xLabelRotation++;
  1344. this.xLabelWidth = cosRotation * originalLabelWidth;
  1345. }
  1346. if (this.xLabelRotation > 0){
  1347. this.endPoint -= Math.sin(toRadians(this.xLabelRotation))*originalLabelWidth + 3;
  1348. }
  1349. }
  1350. else{
  1351. this.xLabelWidth = 0;
  1352. this.xScalePaddingRight = this.padding;
  1353. this.xScalePaddingLeft = this.padding;
  1354. }
  1355. },
  1356. // Needs to be overidden in each Chart type
  1357. // Otherwise we need to pass all the data into the scale class
  1358. calculateYRange: noop,
  1359. drawingArea: function(){
  1360. return this.startPoint - this.endPoint;
  1361. },
  1362. calculateY : function(value){
  1363. var scalingFactor = this.drawingArea() / (this.min - this.max);
  1364. return this.endPoint - (scalingFactor * (value - this.min));
  1365. },
  1366. calculateX : function(index){
  1367. var isRotated = (this.xLabelRotation > 0),
  1368. // innerWidth = (this.offsetGridLines) ? this.width - offsetLeft - this.padding : this.width - (offsetLeft + halfLabelWidth * 2) - this.padding,
  1369. innerWidth = this.width - (this.xScalePaddingLeft + this.xScalePaddingRight),
  1370. valueWidth = innerWidth/Math.max((this.valuesCount - ((this.offsetGridLines) ? 0 : 1)), 1),
  1371. valueOffset = (valueWidth * index) + this.xScalePaddingLeft;
  1372. if (this.offsetGridLines){
  1373. valueOffset += (valueWidth/2);
  1374. }
  1375. return Math.round(valueOffset);
  1376. },
  1377. update : function(newProps){
  1378. helpers.extend(this, newProps);
  1379. this.fit();
  1380. },
  1381. draw : function(){
  1382. var ctx = this.ctx,
  1383. yLabelGap = (this.endPoint - this.startPoint) / this.steps,
  1384. xStart = Math.round(this.xScalePaddingLeft);
  1385. if (this.display){
  1386. ctx.fillStyle = this.textColor;
  1387. ctx.font = this.font;
  1388. each(this.yLabels,function(labelString,index){
  1389. var yLabelCenter = this.endPoint - (yLabelGap * index),
  1390. linePositionY = Math.round(yLabelCenter),
  1391. drawHorizontalLine = this.showHorizontalLines;
  1392. ctx.textAlign = "right";
  1393. ctx.textBaseline = "middle";
  1394. if (this.showLabels){
  1395. ctx.fillText(labelString,xStart - 10,yLabelCenter);
  1396. }
  1397. // This is X axis, so draw it
  1398. if (index === 0 && !drawHorizontalLine){
  1399. drawHorizontalLine = true;
  1400. }
  1401. if (drawHorizontalLine){
  1402. ctx.beginPath();
  1403. }
  1404. if (index > 0){
  1405. // This is a grid line in the centre, so drop that
  1406. ctx.lineWidth = this.gridLineWidth;
  1407. ctx.strokeStyle = this.gridLineColor;
  1408. } else {
  1409. // This is the first line on the scale
  1410. ctx.lineWidth = this.lineWidth;
  1411. ctx.strokeStyle = this.lineColor;
  1412. }
  1413. linePositionY += helpers.aliasPixel(ctx.lineWidth);
  1414. if(drawHorizontalLine){
  1415. ctx.moveTo(xStart, linePositionY);
  1416. ctx.lineTo(this.width, linePositionY);
  1417. ctx.stroke();
  1418. ctx.closePath();
  1419. }
  1420. ctx.lineWidth = this.lineWidth;
  1421. ctx.strokeStyle = this.lineColor;
  1422. ctx.beginPath();
  1423. ctx.moveTo(xStart - 5, linePositionY);
  1424. ctx.lineTo(xStart, linePositionY);
  1425. ctx.stroke();
  1426. ctx.closePath();
  1427. },this);
  1428. each(this.xLabels,function(label,index){
  1429. var xPos = this.calculateX(index) + aliasPixel(this.lineWidth),
  1430. // Check to see if line/bar here and decide where to place the line
  1431. linePos = this.calculateX(index - (this.offsetGridLines ? 0.5 : 0)) + aliasPixel(this.lineWidth),
  1432. isRotated = (this.xLabelRotation > 0),
  1433. drawVerticalLine = this.showVerticalLines;
  1434. // This is Y axis, so draw it
  1435. if (index === 0 && !drawVerticalLine){
  1436. drawVerticalLine = true;
  1437. }
  1438. if (drawVerticalLine){
  1439. ctx.beginPath();
  1440. }
  1441. if (index > 0){
  1442. // This is a grid line in the centre, so drop that
  1443. ctx.lineWidth = this.gridLineWidth;
  1444. ctx.strokeStyle = this.gridLineColor;
  1445. } else {
  1446. // This is the first line on the scale
  1447. ctx.lineWidth = this.lineWidth;
  1448. ctx.strokeStyle = this.lineColor;
  1449. }
  1450. if (drawVerticalLine){
  1451. ctx.moveTo(linePos,this.endPoint);
  1452. ctx.lineTo(linePos,this.startPoint - 3);
  1453. ctx.stroke();
  1454. ctx.closePath();
  1455. }
  1456. ctx.lineWidth = this.lineWidth;
  1457. ctx.strokeStyle = this.lineColor;
  1458. // Small lines at the bottom of the base grid line
  1459. ctx.beginPath();
  1460. ctx.moveTo(linePos,this.endPoint);
  1461. ctx.lineTo(linePos,this.endPoint + 5);
  1462. ctx.stroke();
  1463. ctx.closePath();
  1464. ctx.save();
  1465. ctx.translate(xPos,(isRotated) ? this.endPoint + 12 : this.endPoint + 8);
  1466. ctx.rotate(toRadians(this.xLabelRotation)*-1);
  1467. ctx.font = this.font;
  1468. ctx.textAlign = (isRotated) ? "right" : "center";
  1469. ctx.textBaseline = (isRotated) ? "middle" : "top";
  1470. ctx.fillText(label, 0, 0);
  1471. ctx.restore();
  1472. },this);
  1473. }
  1474. }
  1475. });
  1476. Chart.RadialScale = Chart.Element.extend({
  1477. initialize: function(){
  1478. this.size = min([this.height, this.width]);
  1479. this.drawingArea = (this.display) ? (this.size/2) - (this.fontSize/2 + this.backdropPaddingY) : (this.size/2);
  1480. },
  1481. calculateCenterOffset: function(value){
  1482. // Take into account half font size + the yPadding of the top value
  1483. var scalingFactor = this.drawingArea / (this.max - this.min);
  1484. return (value - this.min) * scalingFactor;
  1485. },
  1486. update : function(){
  1487. if (!this.lineArc){
  1488. this.setScaleSize();
  1489. } else {
  1490. this.drawingArea = (this.display) ? (this.size/2) - (this.fontSize/2 + this.backdropPaddingY) : (this.size/2);
  1491. }
  1492. this.buildYLabels();
  1493. },
  1494. buildYLabels: function(){
  1495. this.yLabels = [];
  1496. var stepDecimalPlaces = getDecimalPlaces(this.stepValue);
  1497. for (var i=0; i<=this.steps; i++){
  1498. this.yLabels.push(template(this.templateString,{value:(this.min + (i * this.stepValue)).toFixed(stepDecimalPlaces)}));
  1499. }
  1500. },
  1501. getCircumference : function(){
  1502. return ((Math.PI*2) / this.valuesCount);
  1503. },
  1504. setScaleSize: function(){
  1505. /*
  1506. * Right, this is really confusing and there is a lot of maths going on here
  1507. * The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9
  1508. *
  1509. * Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif
  1510. *
  1511. * Solution:
  1512. *
  1513. * We assume the radius of the polygon is half the size of the canvas at first
  1514. * at each index we check if the text overlaps.
  1515. *
  1516. * Where it does, we store that angle and that index.
  1517. *
  1518. * After finding the largest index and angle we calculate how much we need to remove
  1519. * from the shape radius to move the point inwards by that x.
  1520. *
  1521. * We average the left and right distances to get the maximum shape radius that can fit in the box
  1522. * along with labels.
  1523. *
  1524. * Once we have that, we can find the centre point for the chart, by taking the x text protrusion
  1525. * on each side, removing that from the size, halving it and adding the left x protrusion width.
  1526. *
  1527. * This will mean we have a shape fitted to the canvas, as large as it can be with the labels
  1528. * and position it in the most space efficient manner
  1529. *
  1530. * https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif
  1531. */
  1532. // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.
  1533. // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points
  1534. var largestPossibleRadius = min([(this.height/2 - this.pointLabelFontSize - 5), this.width/2]),
  1535. pointPosition,
  1536. i,
  1537. textWidth,
  1538. halfTextWidth,
  1539. furthestRight = this.width,
  1540. furthestRightIndex,
  1541. furthestRightAngle,
  1542. furthestLeft = 0,
  1543. furthestLeftIndex,
  1544. furthestLeftAngle,
  1545. xProtrusionLeft,
  1546. xProtrusionRight,
  1547. radiusReductionRight,
  1548. radiusReductionLeft,
  1549. maxWidthRadius;
  1550. this.ctx.font = fontString(this.pointLabelFontSize,this.pointLabelFontStyle,this.pointLabelFontFamily);
  1551. for (i=0;i<this.valuesCount;i++){
  1552. // 5px to space the text slightly out - similar to what we do in the draw function.
  1553. pointPosition = this.getPointPosition(i, largestPossibleRadius);
  1554. textWidth = this.ctx.measureText(template(this.templateString, { value: this.labels[i] })).width + 5;
  1555. if (i === 0 || i === this.valuesCount/2){
  1556. // If we're at index zero, or exactly the middle, we're at exactly the top/bottom
  1557. // of the radar chart, so text will be aligned centrally, so we'll half it and compare
  1558. // w/left and right text sizes
  1559. halfTextWidth = textWidth/2;
  1560. if (pointPosition.x + halfTextWidth > furthestRight) {
  1561. furthestRight = pointPosition.x + halfTextWidth;
  1562. furthestRightIndex = i;
  1563. }
  1564. if (pointPosition.x - halfTextWidth < furthestLeft) {
  1565. furthestLeft = pointPosition.x - halfTextWidth;
  1566. furthestLeftIndex = i;
  1567. }
  1568. }
  1569. else if (i < this.valuesCount/2) {
  1570. // Less than half the values means we'll left align the text
  1571. if (pointPosition.x + textWidth > furthestRight) {
  1572. furthestRight = pointPosition.x + textWidth;
  1573. furthestRightIndex = i;
  1574. }
  1575. }
  1576. else if (i > this.valuesCount/2){
  1577. // More than half the values means we'll right align the text
  1578. if (pointPosition.x - textWidth < furthestLeft) {
  1579. furthestLeft = pointPosition.x - textWidth;
  1580. furthestLeftIndex = i;
  1581. }
  1582. }
  1583. }
  1584. xProtrusionLeft = furthestLeft;
  1585. xProtrusionRight = Math.ceil(furthestRight - this.width);
  1586. furthestRightAngle = this.getIndexAngle(furthestRightIndex);
  1587. furthestLeftAngle = this.getIndexAngle(furthestLeftIndex);
  1588. radiusReductionRight = xProtrusionRight / Math.sin(furthestRightAngle + Math.PI/2);
  1589. radiusReductionLeft = xProtrusionLeft / Math.sin(furthestLeftAngle + Math.PI/2);
  1590. // Ensure we actually need to reduce the size of the chart
  1591. radiusReductionRight = (isNumber(radiusReductionRight)) ? radiusReductionRight : 0;
  1592. radiusReductionLeft = (isNumber(radiusReductionLeft)) ? radiusReductionLeft : 0;
  1593. this.drawingArea = largestPossibleRadius - (radiusReductionLeft + radiusReductionRight)/2;
  1594. //this.drawingArea = min([maxWidthRadius, (this.height - (2 * (this.pointLabelFontSize + 5)))/2])
  1595. this.setCenterPoint(radiusReductionLeft, radiusReductionRight);
  1596. },
  1597. setCenterPoint: function(leftMovement, rightMovement){
  1598. var maxRight = this.width - rightMovement - this.drawingArea,
  1599. maxLeft = leftMovement + this.drawingArea;
  1600. this.xCenter = (maxLeft + maxRight)/2;
  1601. // Always vertically in the centre as the text height doesn't change
  1602. this.yCenter = (this.height/2);
  1603. },
  1604. getIndexAngle : function(index){
  1605. var angleMultiplier = (Math.PI * 2) / this.valuesCount;
  1606. // Start from the top instead of right, so remove a quarter of the circle
  1607. return index * angleMultiplier - (Math.PI/2);
  1608. },
  1609. getPointPosition : function(index, distanceFromCenter){
  1610. var thisAngle = this.getIndexAngle(index);
  1611. return {
  1612. x : (Math.cos(thisAngle) * distanceFromCenter) + this.xCenter,
  1613. y : (Math.sin(thisAngle) * distanceFromCenter) + this.yCenter
  1614. };
  1615. },
  1616. draw: function(){
  1617. if (this.display){
  1618. var ctx = this.ctx;
  1619. each(this.yLabels, function(label, index){
  1620. // Don't draw a centre value
  1621. if (index > 0){
  1622. var yCenterOffset = index * (this.drawingArea/this.steps),
  1623. yHeight = this.yCenter - yCenterOffset,
  1624. pointPosition;
  1625. // Draw circular lines around the scale
  1626. if (this.lineWidth > 0){
  1627. ctx.strokeStyle = this.lineColor;
  1628. ctx.lineWidth = this.lineWidth;
  1629. if(this.lineArc){
  1630. ctx.beginPath();
  1631. ctx.arc(this.xCenter, this.yCenter, yCenterOffset, 0, Math.PI*2);
  1632. ctx.closePath();
  1633. ctx.stroke();
  1634. } else{
  1635. ctx.beginPath();
  1636. for (var i=0;i<this.valuesCount;i++)
  1637. {
  1638. pointPosition = this.getPointPosition(i, this.calculateCenterOffset(this.min + (index * this.stepValue)));
  1639. if (i === 0){
  1640. ctx.moveTo(pointPosition.x, pointPosition.y);
  1641. } else {
  1642. ctx.lineTo(pointPosition.x, pointPosition.y);
  1643. }
  1644. }
  1645. ctx.closePath();
  1646. ctx.stroke();
  1647. }
  1648. }
  1649. if(this.showLabels){
  1650. ctx.font = fontString(this.fontSize,this.fontStyle,this.fontFamily);
  1651. if (this.showLabelBackdrop){
  1652. var labelWidth = ctx.measureText(label).width;
  1653. ctx.fillStyle = this.backdropColor;
  1654. ctx.fillRect(
  1655. this.xCenter - labelWidth/2 - this.backdropPaddingX,
  1656. yHeight - this.fontSize/2 - this.backdropPaddingY,
  1657. labelWidth + this.backdropPaddingX*2,
  1658. this.fontSize + this.backdropPaddingY*2
  1659. );
  1660. }
  1661. ctx.textAlign = 'center';
  1662. ctx.textBaseline = "middle";
  1663. ctx.fillStyle = this.fontColor;
  1664. ctx.fillText(label, this.xCenter, yHeight);
  1665. }
  1666. }
  1667. }, this);
  1668. if (!this.lineArc){
  1669. ctx.lineWidth = this.angleLineWidth;
  1670. ctx.strokeStyle = this.angleLineColor;
  1671. for (var i = this.valuesCount - 1; i >= 0; i--) {
  1672. if (this.angleLineWidth > 0){
  1673. var outerPosition = this.getPointPosition(i, this.calculateCenterOffset(this.max));
  1674. ctx.beginPath();
  1675. ctx.moveTo(this.xCenter, this.yCenter);
  1676. ctx.lineTo(outerPosition.x, outerPosition.y);
  1677. ctx.stroke();
  1678. ctx.closePath();
  1679. }
  1680. // Extra 3px out for some label spacing
  1681. var pointLabelPosition = this.getPointPosition(i, this.calculateCenterOffset(this.max) + 5);
  1682. ctx.font = fontString(this.pointLabelFontSize,this.pointLabelFontStyle,this.pointLabelFontFamily);
  1683. ctx.fillStyle = this.pointLabelFontColor;
  1684. var labelsCount = this.labels.length,
  1685. halfLabelsCount = this.labels.length/2,
  1686. quarterLabelsCount = halfLabelsCount/2,
  1687. upperHalf = (i < quarterLabelsCount || i > labelsCount - quarterLabelsCount),
  1688. exactQuarter = (i === quarterLabelsCount || i === labelsCount - quarterLabelsCount);
  1689. if (i === 0){
  1690. ctx.textAlign = 'center';
  1691. } else if(i === halfLabelsCount){
  1692. ctx.textAlign = 'center';
  1693. } else if (i < halfLabelsCount){
  1694. ctx.textAlign = 'left';
  1695. } else {
  1696. ctx.textAlign = 'right';
  1697. }
  1698. // Set the correct text baseline based on outer positioning
  1699. if (exactQuarter){
  1700. ctx.textBaseline = 'middle';
  1701. } else if (upperHalf){
  1702. ctx.textBaseline = 'bottom';
  1703. } else {
  1704. ctx.textBaseline = 'top';
  1705. }
  1706. ctx.fillText(this.labels[i], pointLabelPosition.x, pointLabelPosition.y);
  1707. }
  1708. }
  1709. }
  1710. }
  1711. });
  1712. // Attach global event to resize each chart instance when the browser resizes
  1713. helpers.addEvent(window, "resize", (function(){
  1714. // Basic debounce of resize function so it doesn't hurt performance when resizing browser.
  1715. var timeout;
  1716. return function(){
  1717. clearTimeout(timeout);
  1718. timeout = setTimeout(function(){
  1719. each(Chart.instances,function(instance){
  1720. // If the responsive flag is set in the chart instance config
  1721. // Cascade the resize event down to the chart.
  1722. if (instance.options.responsive){
  1723. instance.resize(instance.render, true);
  1724. }
  1725. });
  1726. }, 50);
  1727. };
  1728. })());
  1729. if (amd) {
  1730. define(function(){
  1731. return Chart;
  1732. });
  1733. } else if (typeof module === 'object' && module.exports) {
  1734. module.exports = Chart;
  1735. }
  1736. root.Chart = Chart;
  1737. Chart.noConflict = function(){
  1738. root.Chart = previous;
  1739. return Chart;
  1740. };
  1741. }).call(this);
  1742. (function(){
  1743. "use strict";
  1744. var root = this,
  1745. Chart = root.Chart,
  1746. helpers = Chart.helpers;
  1747. var defaultConfig = {
  1748. //Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
  1749. scaleBeginAtZero : true,
  1750. //Boolean - Whether grid lines are shown across the chart
  1751. scaleShowGridLines : true,
  1752. //String - Colour of the grid lines
  1753. scaleGridLineColor : "rgba(0,0,0,.05)",
  1754. //Number - Width of the grid lines
  1755. scaleGridLineWidth : 1,
  1756. //Boolean - Whether to show horizontal lines (except X axis)
  1757. scaleShowHorizontalLines: true,
  1758. //Boolean - Whether to show vertical lines (except Y axis)
  1759. scaleShowVerticalLines: true,
  1760. //Boolean - If there is a stroke on each bar
  1761. barShowStroke : true,
  1762. //Number - Pixel width of the bar stroke
  1763. barStrokeWidth : 2,
  1764. //Number - Spacing between each of the X value sets
  1765. barValueSpacing : 5,
  1766. //Number - Spacing between data sets within X values
  1767. barDatasetSpacing : 1,
  1768. //String - A legend template
  1769. 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>"
  1770. };
  1771. Chart.Type.extend({
  1772. name: "Bar",
  1773. defaults : defaultConfig,
  1774. initialize: function(data){
  1775. //Expose options as a scope variable here so we can access it in the ScaleClass
  1776. var options = this.options;
  1777. this.ScaleClass = Chart.Scale.extend({
  1778. offsetGridLines : true,
  1779. calculateBarX : function(datasetCount, datasetIndex, barIndex){
  1780. //Reusable method for calculating the xPosition of a given bar based on datasetIndex & width of the bar
  1781. var xWidth = this.calculateBaseWidth(),
  1782. xAbsolute = this.calculateX(barIndex) - (xWidth/2),
  1783. barWidth = this.calculateBarWidth(datasetCount);
  1784. return xAbsolute + (barWidth * datasetIndex) + (datasetIndex * options.barDatasetSpacing) + barWidth/2;
  1785. },
  1786. calculateBaseWidth : function(){
  1787. return (this.calculateX(1) - this.calculateX(0)) - (2*options.barValueSpacing);
  1788. },
  1789. calculateBarWidth : function(datasetCount){
  1790. //The padding between datasets is to the right of each bar, providing that there are more than 1 dataset
  1791. var baseWidth = this.calculateBaseWidth() - ((datasetCount - 1) * options.barDatasetSpacing);
  1792. return (baseWidth / datasetCount);
  1793. }
  1794. });
  1795. this.datasets = [];
  1796. //Set up tooltip events on the chart
  1797. if (this.options.showTooltips){
  1798. helpers.bindEvents(this, this.options.tooltipEvents, function(evt){
  1799. var activeBars = (evt.type !== 'mouseout') ? this.getBarsAtEvent(evt) : [];
  1800. this.eachBars(function(bar){
  1801. bar.restore(['fillColor', 'strokeColor']);
  1802. });
  1803. helpers.each(activeBars, function(activeBar){
  1804. activeBar.fillColor = activeBar.highlightFill;
  1805. activeBar.strokeColor = activeBar.highlightStroke;
  1806. });
  1807. this.showTooltip(activeBars);
  1808. });
  1809. }
  1810. //Declare the extension of the default point, to cater for the options passed in to the constructor
  1811. this.BarClass = Chart.Rectangle.extend({
  1812. strokeWidth : this.options.barStrokeWidth,
  1813. showStroke : this.options.barShowStroke,
  1814. ctx : this.chart.ctx
  1815. });
  1816. //Iterate through each of the datasets, and build this into a property of the chart
  1817. helpers.each(data.datasets,function(dataset,datasetIndex){
  1818. var datasetObject = {
  1819. label : dataset.label || null,
  1820. fillColor : dataset.fillColor,
  1821. strokeColor : dataset.strokeColor,
  1822. bars : []
  1823. };
  1824. this.datasets.push(datasetObject);
  1825. helpers.each(dataset.data,function(dataPoint,index){
  1826. //Add a new point for each piece of data, passing any required data to draw.
  1827. datasetObject.bars.push(new this.BarClass({
  1828. value : dataPoint,
  1829. label : data.labels[index],
  1830. datasetLabel: dataset.label,
  1831. strokeColor : dataset.strokeColor,
  1832. fillColor : dataset.fillColor,
  1833. highlightFill : dataset.highlightFill || dataset.fillColor,
  1834. highlightStroke : dataset.highlightStroke || dataset.strokeColor
  1835. }));
  1836. },this);
  1837. },this);
  1838. this.buildScale(data.labels);
  1839. this.BarClass.prototype.base = this.scale.endPoint;
  1840. this.eachBars(function(bar, index, datasetIndex){
  1841. helpers.extend(bar, {
  1842. width : this.scale.calculateBarWidth(this.datasets.length),
  1843. x: this.scale.calculateBarX(this.datasets.length, datasetIndex, index),
  1844. y: this.scale.endPoint
  1845. });
  1846. bar.save();
  1847. }, this);
  1848. this.render();
  1849. },
  1850. update : function(){
  1851. this.scale.update();
  1852. // Reset any highlight colours before updating.
  1853. helpers.each(this.activeElements, function(activeElement){
  1854. activeElement.restore(['fillColor', 'strokeColor']);
  1855. });
  1856. this.eachBars(function(bar){
  1857. bar.save();
  1858. });
  1859. this.render();
  1860. },
  1861. eachBars : function(callback){
  1862. helpers.each(this.datasets,function(dataset, datasetIndex){
  1863. helpers.each(dataset.bars, callback, this, datasetIndex);
  1864. },this);
  1865. },
  1866. getBarsAtEvent : function(e){
  1867. var barsArray = [],
  1868. eventPosition = helpers.getRelativePosition(e),
  1869. datasetIterator = function(dataset){
  1870. barsArray.push(dataset.bars[barIndex]);
  1871. },
  1872. barIndex;
  1873. for (var datasetIndex = 0; datasetIndex < this.datasets.length; datasetIndex++) {
  1874. for (barIndex = 0; barIndex < this.datasets[datasetIndex].bars.length; barIndex++) {
  1875. if (this.datasets[datasetIndex].bars[barIndex].inRange(eventPosition.x,eventPosition.y)){
  1876. helpers.each(this.datasets, datasetIterator);
  1877. return barsArray;
  1878. }
  1879. }
  1880. }
  1881. return barsArray;
  1882. },
  1883. buildScale : function(labels){
  1884. var self = this;
  1885. var dataTotal = function(){
  1886. var values = [];
  1887. self.eachBars(function(bar){
  1888. values.push(bar.value);
  1889. });
  1890. return values;
  1891. };
  1892. var scaleOptions = {
  1893. templateString : this.options.scaleLabel,
  1894. height : this.chart.height,
  1895. width : this.chart.width,
  1896. ctx : this.chart.ctx,
  1897. textColor : this.options.scaleFontColor,
  1898. fontSize : this.options.scaleFontSize,
  1899. fontStyle : this.options.scaleFontStyle,
  1900. fontFamily : this.options.scaleFontFamily,
  1901. valuesCount : labels.length,
  1902. beginAtZero : this.options.scaleBeginAtZero,
  1903. integersOnly : this.options.scaleIntegersOnly,
  1904. calculateYRange: function(currentHeight){
  1905. var updatedRanges = helpers.calculateScaleRange(
  1906. dataTotal(),
  1907. currentHeight,
  1908. this.fontSize,
  1909. this.beginAtZero,
  1910. this.integersOnly
  1911. );
  1912. helpers.extend(this, updatedRanges);
  1913. },
  1914. xLabels : labels,
  1915. font : helpers.fontString(this.options.scaleFontSize, this.options.scaleFontStyle, this.options.scaleFontFamily),
  1916. lineWidth : this.options.scaleLineWidth,
  1917. lineColor : this.options.scaleLineColor,
  1918. showHorizontalLines : this.options.scaleShowHorizontalLines,
  1919. showVerticalLines : this.options.scaleShowVerticalLines,
  1920. gridLineWidth : (this.options.scaleShowGridLines) ? this.options.scaleGridLineWidth : 0,
  1921. gridLineColor : (this.options.scaleShowGridLines) ? this.options.scaleGridLineColor : "rgba(0,0,0,0)",
  1922. padding : (this.options.showScale) ? 0 : (this.options.barShowStroke) ? this.options.barStrokeWidth : 0,
  1923. showLabels : this.options.scaleShowLabels,
  1924. display : this.options.showScale
  1925. };
  1926. if (this.options.scaleOverride){
  1927. helpers.extend(scaleOptions, {
  1928. calculateYRange: helpers.noop,
  1929. steps: this.options.scaleSteps,
  1930. stepValue: this.options.scaleStepWidth,
  1931. min: this.options.scaleStartValue,
  1932. max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth)
  1933. });
  1934. }
  1935. this.scale = new this.ScaleClass(scaleOptions);
  1936. },
  1937. addData : function(valuesArray,label){
  1938. //Map the values array for each of the datasets
  1939. helpers.each(valuesArray,function(value,datasetIndex){
  1940. //Add a new point for each piece of data, passing any required data to draw.
  1941. this.datasets[datasetIndex].bars.push(new this.BarClass({
  1942. value : value,
  1943. label : label,
  1944. x: this.scale.calculateBarX(this.datasets.length, datasetIndex, this.scale.valuesCount+1),
  1945. y: this.scale.endPoint,
  1946. width : this.scale.calculateBarWidth(this.datasets.length),
  1947. base : this.scale.endPoint,
  1948. strokeColor : this.datasets[datasetIndex].strokeColor,
  1949. fillColor : this.datasets[datasetIndex].fillColor
  1950. }));
  1951. },this);
  1952. this.scale.addXLabel(label);
  1953. //Then re-render the chart.
  1954. this.update();
  1955. },
  1956. removeData : function(){
  1957. this.scale.removeXLabel();
  1958. //Then re-render the chart.
  1959. helpers.each(this.datasets,function(dataset){
  1960. dataset.bars.shift();
  1961. },this);
  1962. this.update();
  1963. },
  1964. reflow : function(){
  1965. helpers.extend(this.BarClass.prototype,{
  1966. y: this.scale.endPoint,
  1967. base : this.scale.endPoint
  1968. });
  1969. var newScaleProps = helpers.extend({
  1970. height : this.chart.height,
  1971. width : this.chart.width
  1972. });
  1973. this.scale.update(newScaleProps);
  1974. },
  1975. draw : function(ease){
  1976. var easingDecimal = ease || 1;
  1977. this.clear();
  1978. var ctx = this.chart.ctx;
  1979. this.scale.draw(easingDecimal);
  1980. //Draw all the bars for each dataset
  1981. helpers.each(this.datasets,function(dataset,datasetIndex){
  1982. helpers.each(dataset.bars,function(bar,index){
  1983. if (bar.hasValue()){
  1984. bar.base = this.scale.endPoint;
  1985. //Transition then draw
  1986. bar.transition({
  1987. x : this.scale.calculateBarX(this.datasets.length, datasetIndex, index),
  1988. y : this.scale.calculateY(bar.value),
  1989. width : this.scale.calculateBarWidth(this.datasets.length)
  1990. }, easingDecimal).draw();
  1991. }
  1992. },this);
  1993. },this);
  1994. }
  1995. });
  1996. }).call(this);
  1997. (function(){
  1998. "use strict";
  1999. var root = this,
  2000. Chart = root.Chart,
  2001. //Cache a local reference to Chart.helpers
  2002. helpers = Chart.helpers;
  2003. var defaultConfig = {
  2004. //Boolean - Whether we should show a stroke on each segment
  2005. segmentShowStroke : true,
  2006. //String - The colour of each segment stroke
  2007. segmentStrokeColor : "#fff",
  2008. //Number - The width of each segment stroke
  2009. segmentStrokeWidth : 2,
  2010. //The percentage of the chart that we cut out of the middle.
  2011. percentageInnerCutout : 50,
  2012. //Number - Amount of animation steps
  2013. animationSteps : 100,
  2014. //String - Animation easing effect
  2015. animationEasing : "easeOutBounce",
  2016. //Boolean - Whether we animate the rotation of the Doughnut
  2017. animateRotate : true,
  2018. //Boolean - Whether we animate scaling the Doughnut from the centre
  2019. animateScale : false,
  2020. //String - A legend template
  2021. legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>"
  2022. };
  2023. Chart.Type.extend({
  2024. //Passing in a name registers this chart in the Chart namespace
  2025. name: "Doughnut",
  2026. //Providing a defaults will also register the deafults in the chart namespace
  2027. defaults : defaultConfig,
  2028. //Initialize is fired when the chart is initialized - Data is passed in as a parameter
  2029. //Config is automatically merged by the core of Chart.js, and is available at this.options
  2030. initialize: function(data){
  2031. //Declare segments as a static property to prevent inheriting across the Chart type prototype
  2032. this.segments = [];
  2033. this.outerRadius = (helpers.min([this.chart.width,this.chart.height]) - this.options.segmentStrokeWidth/2)/2;
  2034. this.SegmentArc = Chart.Arc.extend({
  2035. ctx : this.chart.ctx,
  2036. x : this.chart.width/2,
  2037. y : this.chart.height/2
  2038. });
  2039. //Set up tooltip events on the chart
  2040. if (this.options.showTooltips){
  2041. helpers.bindEvents(this, this.options.tooltipEvents, function(evt){
  2042. var activeSegments = (evt.type !== 'mouseout') ? this.getSegmentsAtEvent(evt) : [];
  2043. helpers.each(this.segments,function(segment){
  2044. segment.restore(["fillColor"]);
  2045. });
  2046. helpers.each(activeSegments,function(activeSegment){
  2047. activeSegment.fillColor = activeSegment.highlightColor;
  2048. });
  2049. this.showTooltip(activeSegments);
  2050. });
  2051. }
  2052. this.calculateTotal(data);
  2053. helpers.each(data,function(datapoint, index){
  2054. this.addData(datapoint, index, true);
  2055. },this);
  2056. this.render();
  2057. },
  2058. getSegmentsAtEvent : function(e){
  2059. var segmentsArray = [];
  2060. var location = helpers.getRelativePosition(e);
  2061. helpers.each(this.segments,function(segment){
  2062. if (segment.inRange(location.x,location.y)) segmentsArray.push(segment);
  2063. },this);
  2064. return segmentsArray;
  2065. },
  2066. addData : function(segment, atIndex, silent){
  2067. var index = atIndex || this.segments.length;
  2068. this.segments.splice(index, 0, new this.SegmentArc({
  2069. value : segment.value,
  2070. outerRadius : (this.options.animateScale) ? 0 : this.outerRadius,
  2071. innerRadius : (this.options.animateScale) ? 0 : (this.outerRadius/100) * this.options.percentageInnerCutout,
  2072. fillColor : segment.color,
  2073. highlightColor : segment.highlight || segment.color,
  2074. showStroke : this.options.segmentShowStroke,
  2075. strokeWidth : this.options.segmentStrokeWidth,
  2076. strokeColor : this.options.segmentStrokeColor,
  2077. startAngle : Math.PI * 1.5,
  2078. circumference : (this.options.animateRotate) ? 0 : this.calculateCircumference(segment.value),
  2079. label : segment.label
  2080. }));
  2081. if (!silent){
  2082. this.reflow();
  2083. this.update();
  2084. }
  2085. },
  2086. calculateCircumference : function(value){
  2087. return (Math.PI*2)*(Math.abs(value) / this.total);
  2088. },
  2089. calculateTotal : function(data){
  2090. this.total = 0;
  2091. helpers.each(data,function(segment){
  2092. this.total += Math.abs(segment.value);
  2093. },this);
  2094. },
  2095. update : function(){
  2096. this.calculateTotal(this.segments);
  2097. // Reset any highlight colours before updating.
  2098. helpers.each(this.activeElements, function(activeElement){
  2099. activeElement.restore(['fillColor']);
  2100. });
  2101. helpers.each(this.segments,function(segment){
  2102. segment.save();
  2103. });
  2104. this.render();
  2105. },
  2106. removeData: function(atIndex){
  2107. var indexToDelete = (helpers.isNumber(atIndex)) ? atIndex : this.segments.length-1;
  2108. this.segments.splice(indexToDelete, 1);
  2109. this.reflow();
  2110. this.update();
  2111. },
  2112. reflow : function(){
  2113. helpers.extend(this.SegmentArc.prototype,{
  2114. x : this.chart.width/2,
  2115. y : this.chart.height/2
  2116. });
  2117. this.outerRadius = (helpers.min([this.chart.width,this.chart.height]) - this.options.segmentStrokeWidth/2)/2;
  2118. helpers.each(this.segments, function(segment){
  2119. segment.update({
  2120. outerRadius : this.outerRadius,
  2121. innerRadius : (this.outerRadius/100) * this.options.percentageInnerCutout
  2122. });
  2123. }, this);
  2124. },
  2125. draw : function(easeDecimal){
  2126. var animDecimal = (easeDecimal) ? easeDecimal : 1;
  2127. this.clear();
  2128. helpers.each(this.segments,function(segment,index){
  2129. segment.transition({
  2130. circumference : this.calculateCircumference(segment.value),
  2131. outerRadius : this.outerRadius,
  2132. innerRadius : (this.outerRadius/100) * this.options.percentageInnerCutout
  2133. },animDecimal);
  2134. segment.endAngle = segment.startAngle + segment.circumference;
  2135. segment.draw();
  2136. if (index === 0){
  2137. segment.startAngle = Math.PI * 1.5;
  2138. }
  2139. //Check to see if it's the last segment, if not get the next and update the start angle
  2140. if (index < this.segments.length-1){
  2141. this.segments[index+1].startAngle = segment.endAngle;
  2142. }
  2143. },this);
  2144. }
  2145. });
  2146. Chart.types.Doughnut.extend({
  2147. name : "Pie",
  2148. defaults : helpers.merge(defaultConfig,{percentageInnerCutout : 0})
  2149. });
  2150. }).call(this);
  2151. (function(){
  2152. "use strict";
  2153. var root = this,
  2154. Chart = root.Chart,
  2155. helpers = Chart.helpers;
  2156. var defaultConfig = {
  2157. ///Boolean - Whether grid lines are shown across the chart
  2158. scaleShowGridLines : true,
  2159. //String - Colour of the grid lines
  2160. scaleGridLineColor : "rgba(0,0,0,.05)",
  2161. //Number - Width of the grid lines
  2162. scaleGridLineWidth : 1,
  2163. //Boolean - Whether to show horizontal lines (except X axis)
  2164. scaleShowHorizontalLines: true,
  2165. //Boolean - Whether to show vertical lines (except Y axis)
  2166. scaleShowVerticalLines: true,
  2167. //Boolean - Whether the line is curved between points
  2168. bezierCurve : true,
  2169. //Number - Tension of the bezier curve between points
  2170. bezierCurveTension : 0.4,
  2171. //Boolean - Whether to show a dot for each point
  2172. pointDot : true,
  2173. //Number - Radius of each point dot in pixels
  2174. pointDotRadius : 4,
  2175. //Number - Pixel width of point dot stroke
  2176. pointDotStrokeWidth : 1,
  2177. //Number - amount extra to add to the radius to cater for hit detection outside the drawn point
  2178. pointHitDetectionRadius : 20,
  2179. //Boolean - Whether to show a stroke for datasets
  2180. datasetStroke : true,
  2181. //Number - Pixel width of dataset stroke
  2182. datasetStrokeWidth : 2,
  2183. //Boolean - Whether to fill the dataset with a colour
  2184. datasetFill : true,
  2185. //String - A legend template
  2186. legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].strokeColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
  2187. };
  2188. Chart.Type.extend({
  2189. name: "Line",
  2190. defaults : defaultConfig,
  2191. initialize: function(data){
  2192. //Declare the extension of the default point, to cater for the options passed in to the constructor
  2193. this.PointClass = Chart.Point.extend({
  2194. strokeWidth : this.options.pointDotStrokeWidth,
  2195. radius : this.options.pointDotRadius,
  2196. display: this.options.pointDot,
  2197. hitDetectionRadius : this.options.pointHitDetectionRadius,
  2198. ctx : this.chart.ctx,
  2199. inRange : function(mouseX){
  2200. return (Math.pow(mouseX-this.x, 2) < Math.pow(this.radius + this.hitDetectionRadius,2));
  2201. }
  2202. });
  2203. this.datasets = [];
  2204. //Set up tooltip events on the chart
  2205. if (this.options.showTooltips){
  2206. helpers.bindEvents(this, this.options.tooltipEvents, function(evt){
  2207. var activePoints = (evt.type !== 'mouseout') ? this.getPointsAtEvent(evt) : [];
  2208. this.eachPoints(function(point){
  2209. point.restore(['fillColor', 'strokeColor']);
  2210. });
  2211. helpers.each(activePoints, function(activePoint){
  2212. activePoint.fillColor = activePoint.highlightFill;
  2213. activePoint.strokeColor = activePoint.highlightStroke;
  2214. });
  2215. this.showTooltip(activePoints);
  2216. });
  2217. }
  2218. //Iterate through each of the datasets, and build this into a property of the chart
  2219. helpers.each(data.datasets,function(dataset){
  2220. var datasetObject = {
  2221. label : dataset.label || null,
  2222. fillColor : dataset.fillColor,
  2223. strokeColor : dataset.strokeColor,
  2224. pointColor : dataset.pointColor,
  2225. pointStrokeColor : dataset.pointStrokeColor,
  2226. points : []
  2227. };
  2228. this.datasets.push(datasetObject);
  2229. helpers.each(dataset.data,function(dataPoint,index){
  2230. //Add a new point for each piece of data, passing any required data to draw.
  2231. datasetObject.points.push(new this.PointClass({
  2232. value : dataPoint,
  2233. label : data.labels[index],
  2234. datasetLabel: dataset.label,
  2235. strokeColor : dataset.pointStrokeColor,
  2236. fillColor : dataset.pointColor,
  2237. highlightFill : dataset.pointHighlightFill || dataset.pointColor,
  2238. highlightStroke : dataset.pointHighlightStroke || dataset.pointStrokeColor
  2239. }));
  2240. },this);
  2241. this.buildScale(data.labels);
  2242. this.eachPoints(function(point, index){
  2243. helpers.extend(point, {
  2244. x: this.scale.calculateX(index),
  2245. y: this.scale.endPoint
  2246. });
  2247. point.save();
  2248. }, this);
  2249. },this);
  2250. this.render();
  2251. },
  2252. update : function(){
  2253. this.scale.update();
  2254. // Reset any highlight colours before updating.
  2255. helpers.each(this.activeElements, function(activeElement){
  2256. activeElement.restore(['fillColor', 'strokeColor']);
  2257. });
  2258. this.eachPoints(function(point){
  2259. point.save();
  2260. });
  2261. this.render();
  2262. },
  2263. eachPoints : function(callback){
  2264. helpers.each(this.datasets,function(dataset){
  2265. helpers.each(dataset.points,callback,this);
  2266. },this);
  2267. },
  2268. getPointsAtEvent : function(e){
  2269. var pointsArray = [],
  2270. eventPosition = helpers.getRelativePosition(e);
  2271. helpers.each(this.datasets,function(dataset){
  2272. helpers.each(dataset.points,function(point){
  2273. if (point.inRange(eventPosition.x,eventPosition.y)) pointsArray.push(point);
  2274. });
  2275. },this);
  2276. return pointsArray;
  2277. },
  2278. buildScale : function(labels){
  2279. var self = this;
  2280. var dataTotal = function(){
  2281. var values = [];
  2282. self.eachPoints(function(point){
  2283. values.push(point.value);
  2284. });
  2285. return values;
  2286. };
  2287. var scaleOptions = {
  2288. templateString : this.options.scaleLabel,
  2289. height : this.chart.height,
  2290. width : this.chart.width,
  2291. ctx : this.chart.ctx,
  2292. textColor : this.options.scaleFontColor,
  2293. fontSize : this.options.scaleFontSize,
  2294. fontStyle : this.options.scaleFontStyle,
  2295. fontFamily : this.options.scaleFontFamily,
  2296. valuesCount : labels.length,
  2297. beginAtZero : this.options.scaleBeginAtZero,
  2298. integersOnly : this.options.scaleIntegersOnly,
  2299. calculateYRange : function(currentHeight){
  2300. var updatedRanges = helpers.calculateScaleRange(
  2301. dataTotal(),
  2302. currentHeight,
  2303. this.fontSize,
  2304. this.beginAtZero,
  2305. this.integersOnly
  2306. );
  2307. helpers.extend(this, updatedRanges);
  2308. },
  2309. xLabels : labels,
  2310. font : helpers.fontString(this.options.scaleFontSize, this.options.scaleFontStyle, this.options.scaleFontFamily),
  2311. lineWidth : this.options.scaleLineWidth,
  2312. lineColor : this.options.scaleLineColor,
  2313. showHorizontalLines : this.options.scaleShowHorizontalLines,
  2314. showVerticalLines : this.options.scaleShowVerticalLines,
  2315. gridLineWidth : (this.options.scaleShowGridLines) ? this.options.scaleGridLineWidth : 0,
  2316. gridLineColor : (this.options.scaleShowGridLines) ? this.options.scaleGridLineColor : "rgba(0,0,0,0)",
  2317. padding: (this.options.showScale) ? 0 : this.options.pointDotRadius + this.options.pointDotStrokeWidth,
  2318. showLabels : this.options.scaleShowLabels,
  2319. display : this.options.showScale
  2320. };
  2321. if (this.options.scaleOverride){
  2322. helpers.extend(scaleOptions, {
  2323. calculateYRange: helpers.noop,
  2324. steps: this.options.scaleSteps,
  2325. stepValue: this.options.scaleStepWidth,
  2326. min: this.options.scaleStartValue,
  2327. max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth)
  2328. });
  2329. }
  2330. this.scale = new Chart.Scale(scaleOptions);
  2331. },
  2332. addData : function(valuesArray,label){
  2333. //Map the values array for each of the datasets
  2334. helpers.each(valuesArray,function(value,datasetIndex){
  2335. //Add a new point for each piece of data, passing any required data to draw.
  2336. this.datasets[datasetIndex].points.push(new this.PointClass({
  2337. value : value,
  2338. label : label,
  2339. x: this.scale.calculateX(this.scale.valuesCount+1),
  2340. y: this.scale.endPoint,
  2341. strokeColor : this.datasets[datasetIndex].pointStrokeColor,
  2342. fillColor : this.datasets[datasetIndex].pointColor
  2343. }));
  2344. },this);
  2345. this.scale.addXLabel(label);
  2346. //Then re-render the chart.
  2347. this.update();
  2348. },
  2349. removeData : function(){
  2350. this.scale.removeXLabel();
  2351. //Then re-render the chart.
  2352. helpers.each(this.datasets,function(dataset){
  2353. dataset.points.shift();
  2354. },this);
  2355. this.update();
  2356. },
  2357. reflow : function(){
  2358. var newScaleProps = helpers.extend({
  2359. height : this.chart.height,
  2360. width : this.chart.width
  2361. });
  2362. this.scale.update(newScaleProps);
  2363. },
  2364. draw : function(ease){
  2365. var easingDecimal = ease || 1;
  2366. this.clear();
  2367. var ctx = this.chart.ctx;
  2368. // Some helper methods for getting the next/prev points
  2369. var hasValue = function(item){
  2370. return item.value !== null;
  2371. },
  2372. nextPoint = function(point, collection, index){
  2373. return helpers.findNextWhere(collection, hasValue, index) || point;
  2374. },
  2375. previousPoint = function(point, collection, index){
  2376. return helpers.findPreviousWhere(collection, hasValue, index) || point;
  2377. };
  2378. this.scale.draw(easingDecimal);
  2379. helpers.each(this.datasets,function(dataset){
  2380. var pointsWithValues = helpers.where(dataset.points, hasValue);
  2381. //Transition each point first so that the line and point drawing isn't out of sync
  2382. //We can use this extra loop to calculate the control points of this dataset also in this loop
  2383. helpers.each(dataset.points, function(point, index){
  2384. if (point.hasValue()){
  2385. point.transition({
  2386. y : this.scale.calculateY(point.value),
  2387. x : this.scale.calculateX(index)
  2388. }, easingDecimal);
  2389. }
  2390. },this);
  2391. // Control points need to be calculated in a seperate loop, because we need to know the current x/y of the point
  2392. // This would cause issues when there is no animation, because the y of the next point would be 0, so beziers would be skewed
  2393. if (this.options.bezierCurve){
  2394. helpers.each(pointsWithValues, function(point, index){
  2395. var tension = (index > 0 && index < pointsWithValues.length - 1) ? this.options.bezierCurveTension : 0;
  2396. point.controlPoints = helpers.splineCurve(
  2397. previousPoint(point, pointsWithValues, index),
  2398. point,
  2399. nextPoint(point, pointsWithValues, index),
  2400. tension
  2401. );
  2402. // Prevent the bezier going outside of the bounds of the graph
  2403. // Cap puter bezier handles to the upper/lower scale bounds
  2404. if (point.controlPoints.outer.y > this.scale.endPoint){
  2405. point.controlPoints.outer.y = this.scale.endPoint;
  2406. }
  2407. else if (point.controlPoints.outer.y < this.scale.startPoint){
  2408. point.controlPoints.outer.y = this.scale.startPoint;
  2409. }
  2410. // Cap inner bezier handles to the upper/lower scale bounds
  2411. if (point.controlPoints.inner.y > this.scale.endPoint){
  2412. point.controlPoints.inner.y = this.scale.endPoint;
  2413. }
  2414. else if (point.controlPoints.inner.y < this.scale.startPoint){
  2415. point.controlPoints.inner.y = this.scale.startPoint;
  2416. }
  2417. },this);
  2418. }
  2419. //Draw the line between all the points
  2420. ctx.lineWidth = this.options.datasetStrokeWidth;
  2421. ctx.strokeStyle = dataset.strokeColor;
  2422. ctx.beginPath();
  2423. helpers.each(pointsWithValues, function(point, index){
  2424. if (index === 0){
  2425. ctx.moveTo(point.x, point.y);
  2426. }
  2427. else{
  2428. if(this.options.bezierCurve){
  2429. var previous = previousPoint(point, pointsWithValues, index);
  2430. ctx.bezierCurveTo(
  2431. previous.controlPoints.outer.x,
  2432. previous.controlPoints.outer.y,
  2433. point.controlPoints.inner.x,
  2434. point.controlPoints.inner.y,
  2435. point.x,
  2436. point.y
  2437. );
  2438. }
  2439. else{
  2440. ctx.lineTo(point.x,point.y);
  2441. }
  2442. }
  2443. }, this);
  2444. ctx.stroke();
  2445. if (this.options.datasetFill && pointsWithValues.length > 0){
  2446. //Round off the line by going to the base of the chart, back to the start, then fill.
  2447. ctx.lineTo(pointsWithValues[pointsWithValues.length - 1].x, this.scale.endPoint);
  2448. ctx.lineTo(pointsWithValues[0].x, this.scale.endPoint);
  2449. ctx.fillStyle = dataset.fillColor;
  2450. ctx.closePath();
  2451. ctx.fill();
  2452. }
  2453. //Now draw the points over the line
  2454. //A little inefficient double looping, but better than the line
  2455. //lagging behind the point positions
  2456. helpers.each(pointsWithValues,function(point){
  2457. point.draw();
  2458. });
  2459. },this);
  2460. }
  2461. });
  2462. }).call(this);
  2463. (function(){
  2464. "use strict";
  2465. var root = this,
  2466. Chart = root.Chart,
  2467. //Cache a local reference to Chart.helpers
  2468. helpers = Chart.helpers;
  2469. var defaultConfig = {
  2470. //Boolean - Show a backdrop to the scale label
  2471. scaleShowLabelBackdrop : true,
  2472. //String - The colour of the label backdrop
  2473. scaleBackdropColor : "rgba(255,255,255,0.75)",
  2474. // Boolean - Whether the scale should begin at zero
  2475. scaleBeginAtZero : true,
  2476. //Number - The backdrop padding above & below the label in pixels
  2477. scaleBackdropPaddingY : 2,
  2478. //Number - The backdrop padding to the side of the label in pixels
  2479. scaleBackdropPaddingX : 2,
  2480. //Boolean - Show line for each value in the scale
  2481. scaleShowLine : true,
  2482. //Boolean - Stroke a line around each segment in the chart
  2483. segmentShowStroke : true,
  2484. //String - The colour of the stroke on each segement.
  2485. segmentStrokeColor : "#fff",
  2486. //Number - The width of the stroke value in pixels
  2487. segmentStrokeWidth : 2,
  2488. //Number - Amount of animation steps
  2489. animationSteps : 100,
  2490. //String - Animation easing effect.
  2491. animationEasing : "easeOutBounce",
  2492. //Boolean - Whether to animate the rotation of the chart
  2493. animateRotate : true,
  2494. //Boolean - Whether to animate scaling the chart from the centre
  2495. animateScale : false,
  2496. //String - A legend template
  2497. legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>"
  2498. };
  2499. Chart.Type.extend({
  2500. //Passing in a name registers this chart in the Chart namespace
  2501. name: "PolarArea",
  2502. //Providing a defaults will also register the deafults in the chart namespace
  2503. defaults : defaultConfig,
  2504. //Initialize is fired when the chart is initialized - Data is passed in as a parameter
  2505. //Config is automatically merged by the core of Chart.js, and is available at this.options
  2506. initialize: function(data){
  2507. this.segments = [];
  2508. //Declare segment class as a chart instance specific class, so it can share props for this instance
  2509. this.SegmentArc = Chart.Arc.extend({
  2510. showStroke : this.options.segmentShowStroke,
  2511. strokeWidth : this.options.segmentStrokeWidth,
  2512. strokeColor : this.options.segmentStrokeColor,
  2513. ctx : this.chart.ctx,
  2514. innerRadius : 0,
  2515. x : this.chart.width/2,
  2516. y : this.chart.height/2
  2517. });
  2518. this.scale = new Chart.RadialScale({
  2519. display: this.options.showScale,
  2520. fontStyle: this.options.scaleFontStyle,
  2521. fontSize: this.options.scaleFontSize,
  2522. fontFamily: this.options.scaleFontFamily,
  2523. fontColor: this.options.scaleFontColor,
  2524. showLabels: this.options.scaleShowLabels,
  2525. showLabelBackdrop: this.options.scaleShowLabelBackdrop,
  2526. backdropColor: this.options.scaleBackdropColor,
  2527. backdropPaddingY : this.options.scaleBackdropPaddingY,
  2528. backdropPaddingX: this.options.scaleBackdropPaddingX,
  2529. lineWidth: (this.options.scaleShowLine) ? this.options.scaleLineWidth : 0,
  2530. lineColor: this.options.scaleLineColor,
  2531. lineArc: true,
  2532. width: this.chart.width,
  2533. height: this.chart.height,
  2534. xCenter: this.chart.width/2,
  2535. yCenter: this.chart.height/2,
  2536. ctx : this.chart.ctx,
  2537. templateString: this.options.scaleLabel,
  2538. valuesCount: data.length
  2539. });
  2540. this.updateScaleRange(data);
  2541. this.scale.update();
  2542. helpers.each(data,function(segment,index){
  2543. this.addData(segment,index,true);
  2544. },this);
  2545. //Set up tooltip events on the chart
  2546. if (this.options.showTooltips){
  2547. helpers.bindEvents(this, this.options.tooltipEvents, function(evt){
  2548. var activeSegments = (evt.type !== 'mouseout') ? this.getSegmentsAtEvent(evt) : [];
  2549. helpers.each(this.segments,function(segment){
  2550. segment.restore(["fillColor"]);
  2551. });
  2552. helpers.each(activeSegments,function(activeSegment){
  2553. activeSegment.fillColor = activeSegment.highlightColor;
  2554. });
  2555. this.showTooltip(activeSegments);
  2556. });
  2557. }
  2558. this.render();
  2559. },
  2560. getSegmentsAtEvent : function(e){
  2561. var segmentsArray = [];
  2562. var location = helpers.getRelativePosition(e);
  2563. helpers.each(this.segments,function(segment){
  2564. if (segment.inRange(location.x,location.y)) segmentsArray.push(segment);
  2565. },this);
  2566. return segmentsArray;
  2567. },
  2568. addData : function(segment, atIndex, silent){
  2569. var index = atIndex || this.segments.length;
  2570. this.segments.splice(index, 0, new this.SegmentArc({
  2571. fillColor: segment.color,
  2572. highlightColor: segment.highlight || segment.color,
  2573. label: segment.label,
  2574. value: segment.value,
  2575. outerRadius: (this.options.animateScale) ? 0 : this.scale.calculateCenterOffset(segment.value),
  2576. circumference: (this.options.animateRotate) ? 0 : this.scale.getCircumference(),
  2577. startAngle: Math.PI * 1.5
  2578. }));
  2579. if (!silent){
  2580. this.reflow();
  2581. this.update();
  2582. }
  2583. },
  2584. removeData: function(atIndex){
  2585. var indexToDelete = (helpers.isNumber(atIndex)) ? atIndex : this.segments.length-1;
  2586. this.segments.splice(indexToDelete, 1);
  2587. this.reflow();
  2588. this.update();
  2589. },
  2590. calculateTotal: function(data){
  2591. this.total = 0;
  2592. helpers.each(data,function(segment){
  2593. this.total += segment.value;
  2594. },this);
  2595. this.scale.valuesCount = this.segments.length;
  2596. },
  2597. updateScaleRange: function(datapoints){
  2598. var valuesArray = [];
  2599. helpers.each(datapoints,function(segment){
  2600. valuesArray.push(segment.value);
  2601. });
  2602. var scaleSizes = (this.options.scaleOverride) ?
  2603. {
  2604. steps: this.options.scaleSteps,
  2605. stepValue: this.options.scaleStepWidth,
  2606. min: this.options.scaleStartValue,
  2607. max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth)
  2608. } :
  2609. helpers.calculateScaleRange(
  2610. valuesArray,
  2611. helpers.min([this.chart.width, this.chart.height])/2,
  2612. this.options.scaleFontSize,
  2613. this.options.scaleBeginAtZero,
  2614. this.options.scaleIntegersOnly
  2615. );
  2616. helpers.extend(
  2617. this.scale,
  2618. scaleSizes,
  2619. {
  2620. size: helpers.min([this.chart.width, this.chart.height]),
  2621. xCenter: this.chart.width/2,
  2622. yCenter: this.chart.height/2
  2623. }
  2624. );
  2625. },
  2626. update : function(){
  2627. this.calculateTotal(this.segments);
  2628. helpers.each(this.segments,function(segment){
  2629. segment.save();
  2630. });
  2631. this.reflow();
  2632. this.render();
  2633. },
  2634. reflow : function(){
  2635. helpers.extend(this.SegmentArc.prototype,{
  2636. x : this.chart.width/2,
  2637. y : this.chart.height/2
  2638. });
  2639. this.updateScaleRange(this.segments);
  2640. this.scale.update();
  2641. helpers.extend(this.scale,{
  2642. xCenter: this.chart.width/2,
  2643. yCenter: this.chart.height/2
  2644. });
  2645. helpers.each(this.segments, function(segment){
  2646. segment.update({
  2647. outerRadius : this.scale.calculateCenterOffset(segment.value)
  2648. });
  2649. }, this);
  2650. },
  2651. draw : function(ease){
  2652. var easingDecimal = ease || 1;
  2653. //Clear & draw the canvas
  2654. this.clear();
  2655. helpers.each(this.segments,function(segment, index){
  2656. segment.transition({
  2657. circumference : this.scale.getCircumference(),
  2658. outerRadius : this.scale.calculateCenterOffset(segment.value)
  2659. },easingDecimal);
  2660. segment.endAngle = segment.startAngle + segment.circumference;
  2661. // If we've removed the first segment we need to set the first one to
  2662. // start at the top.
  2663. if (index === 0){
  2664. segment.startAngle = Math.PI * 1.5;
  2665. }
  2666. //Check to see if it's the last segment, if not get the next and update the start angle
  2667. if (index < this.segments.length - 1){
  2668. this.segments[index+1].startAngle = segment.endAngle;
  2669. }
  2670. segment.draw();
  2671. }, this);
  2672. this.scale.draw();
  2673. }
  2674. });
  2675. }).call(this);
  2676. (function(){
  2677. "use strict";
  2678. var root = this,
  2679. Chart = root.Chart,
  2680. helpers = Chart.helpers;
  2681. Chart.Type.extend({
  2682. name: "Radar",
  2683. defaults:{
  2684. //Boolean - Whether to show lines for each scale point
  2685. scaleShowLine : true,
  2686. //Boolean - Whether we show the angle lines out of the radar
  2687. angleShowLineOut : true,
  2688. //Boolean - Whether to show labels on the scale
  2689. scaleShowLabels : false,
  2690. // Boolean - Whether the scale should begin at zero
  2691. scaleBeginAtZero : true,
  2692. //String - Colour of the angle line
  2693. angleLineColor : "rgba(0,0,0,.1)",
  2694. //Number - Pixel width of the angle line
  2695. angleLineWidth : 1,
  2696. //String - Point label font declaration
  2697. pointLabelFontFamily : "'Arial'",
  2698. //String - Point label font weight
  2699. pointLabelFontStyle : "normal",
  2700. //Number - Point label font size in pixels
  2701. pointLabelFontSize : 10,
  2702. //String - Point label font colour
  2703. pointLabelFontColor : "#666",
  2704. //Boolean - Whether to show a dot for each point
  2705. pointDot : true,
  2706. //Number - Radius of each point dot in pixels
  2707. pointDotRadius : 3,
  2708. //Number - Pixel width of point dot stroke
  2709. pointDotStrokeWidth : 1,
  2710. //Number - amount extra to add to the radius to cater for hit detection outside the drawn point
  2711. pointHitDetectionRadius : 20,
  2712. //Boolean - Whether to show a stroke for datasets
  2713. datasetStroke : true,
  2714. //Number - Pixel width of dataset stroke
  2715. datasetStrokeWidth : 2,
  2716. //Boolean - Whether to fill the dataset with a colour
  2717. datasetFill : true,
  2718. //String - A legend template
  2719. legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].strokeColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
  2720. },
  2721. initialize: function(data){
  2722. this.PointClass = Chart.Point.extend({
  2723. strokeWidth : this.options.pointDotStrokeWidth,
  2724. radius : this.options.pointDotRadius,
  2725. display: this.options.pointDot,
  2726. hitDetectionRadius : this.options.pointHitDetectionRadius,
  2727. ctx : this.chart.ctx
  2728. });
  2729. this.datasets = [];
  2730. this.buildScale(data);
  2731. //Set up tooltip events on the chart
  2732. if (this.options.showTooltips){
  2733. helpers.bindEvents(this, this.options.tooltipEvents, function(evt){
  2734. var activePointsCollection = (evt.type !== 'mouseout') ? this.getPointsAtEvent(evt) : [];
  2735. this.eachPoints(function(point){
  2736. point.restore(['fillColor', 'strokeColor']);
  2737. });
  2738. helpers.each(activePointsCollection, function(activePoint){
  2739. activePoint.fillColor = activePoint.highlightFill;
  2740. activePoint.strokeColor = activePoint.highlightStroke;
  2741. });
  2742. this.showTooltip(activePointsCollection);
  2743. });
  2744. }
  2745. //Iterate through each of the datasets, and build this into a property of the chart
  2746. helpers.each(data.datasets,function(dataset){
  2747. var datasetObject = {
  2748. label: dataset.label || null,
  2749. fillColor : dataset.fillColor,
  2750. strokeColor : dataset.strokeColor,
  2751. pointColor : dataset.pointColor,
  2752. pointStrokeColor : dataset.pointStrokeColor,
  2753. points : []
  2754. };
  2755. this.datasets.push(datasetObject);
  2756. helpers.each(dataset.data,function(dataPoint,index){
  2757. //Add a new point for each piece of data, passing any required data to draw.
  2758. var pointPosition;
  2759. if (!this.scale.animation){
  2760. pointPosition = this.scale.getPointPosition(index, this.scale.calculateCenterOffset(dataPoint));
  2761. }
  2762. datasetObject.points.push(new this.PointClass({
  2763. value : dataPoint,
  2764. label : data.labels[index],
  2765. datasetLabel: dataset.label,
  2766. x: (this.options.animation) ? this.scale.xCenter : pointPosition.x,
  2767. y: (this.options.animation) ? this.scale.yCenter : pointPosition.y,
  2768. strokeColor : dataset.pointStrokeColor,
  2769. fillColor : dataset.pointColor,
  2770. highlightFill : dataset.pointHighlightFill || dataset.pointColor,
  2771. highlightStroke : dataset.pointHighlightStroke || dataset.pointStrokeColor
  2772. }));
  2773. },this);
  2774. },this);
  2775. this.render();
  2776. },
  2777. eachPoints : function(callback){
  2778. helpers.each(this.datasets,function(dataset){
  2779. helpers.each(dataset.points,callback,this);
  2780. },this);
  2781. },
  2782. getPointsAtEvent : function(evt){
  2783. var mousePosition = helpers.getRelativePosition(evt),
  2784. fromCenter = helpers.getAngleFromPoint({
  2785. x: this.scale.xCenter,
  2786. y: this.scale.yCenter
  2787. }, mousePosition);
  2788. var anglePerIndex = (Math.PI * 2) /this.scale.valuesCount,
  2789. pointIndex = Math.round((fromCenter.angle - Math.PI * 1.5) / anglePerIndex),
  2790. activePointsCollection = [];
  2791. // If we're at the top, make the pointIndex 0 to get the first of the array.
  2792. if (pointIndex >= this.scale.valuesCount || pointIndex < 0){
  2793. pointIndex = 0;
  2794. }
  2795. if (fromCenter.distance <= this.scale.drawingArea){
  2796. helpers.each(this.datasets, function(dataset){
  2797. activePointsCollection.push(dataset.points[pointIndex]);
  2798. });
  2799. }
  2800. return activePointsCollection;
  2801. },
  2802. buildScale : function(data){
  2803. this.scale = new Chart.RadialScale({
  2804. display: this.options.showScale,
  2805. fontStyle: this.options.scaleFontStyle,
  2806. fontSize: this.options.scaleFontSize,
  2807. fontFamily: this.options.scaleFontFamily,
  2808. fontColor: this.options.scaleFontColor,
  2809. showLabels: this.options.scaleShowLabels,
  2810. showLabelBackdrop: this.options.scaleShowLabelBackdrop,
  2811. backdropColor: this.options.scaleBackdropColor,
  2812. backdropPaddingY : this.options.scaleBackdropPaddingY,
  2813. backdropPaddingX: this.options.scaleBackdropPaddingX,
  2814. lineWidth: (this.options.scaleShowLine) ? this.options.scaleLineWidth : 0,
  2815. lineColor: this.options.scaleLineColor,
  2816. angleLineColor : this.options.angleLineColor,
  2817. angleLineWidth : (this.options.angleShowLineOut) ? this.options.angleLineWidth : 0,
  2818. // Point labels at the edge of each line
  2819. pointLabelFontColor : this.options.pointLabelFontColor,
  2820. pointLabelFontSize : this.options.pointLabelFontSize,
  2821. pointLabelFontFamily : this.options.pointLabelFontFamily,
  2822. pointLabelFontStyle : this.options.pointLabelFontStyle,
  2823. height : this.chart.height,
  2824. width: this.chart.width,
  2825. xCenter: this.chart.width/2,
  2826. yCenter: this.chart.height/2,
  2827. ctx : this.chart.ctx,
  2828. templateString: this.options.scaleLabel,
  2829. labels: data.labels,
  2830. valuesCount: data.datasets[0].data.length
  2831. });
  2832. this.scale.setScaleSize();
  2833. this.updateScaleRange(data.datasets);
  2834. this.scale.buildYLabels();
  2835. },
  2836. updateScaleRange: function(datasets){
  2837. var valuesArray = (function(){
  2838. var totalDataArray = [];
  2839. helpers.each(datasets,function(dataset){
  2840. if (dataset.data){
  2841. totalDataArray = totalDataArray.concat(dataset.data);
  2842. }
  2843. else {
  2844. helpers.each(dataset.points, function(point){
  2845. totalDataArray.push(point.value);
  2846. });
  2847. }
  2848. });
  2849. return totalDataArray;
  2850. })();
  2851. var scaleSizes = (this.options.scaleOverride) ?
  2852. {
  2853. steps: this.options.scaleSteps,
  2854. stepValue: this.options.scaleStepWidth,
  2855. min: this.options.scaleStartValue,
  2856. max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth)
  2857. } :
  2858. helpers.calculateScaleRange(
  2859. valuesArray,
  2860. helpers.min([this.chart.width, this.chart.height])/2,
  2861. this.options.scaleFontSize,
  2862. this.options.scaleBeginAtZero,
  2863. this.options.scaleIntegersOnly
  2864. );
  2865. helpers.extend(
  2866. this.scale,
  2867. scaleSizes
  2868. );
  2869. },
  2870. addData : function(valuesArray,label){
  2871. //Map the values array for each of the datasets
  2872. this.scale.valuesCount++;
  2873. helpers.each(valuesArray,function(value,datasetIndex){
  2874. var pointPosition = this.scale.getPointPosition(this.scale.valuesCount, this.scale.calculateCenterOffset(value));
  2875. this.datasets[datasetIndex].points.push(new this.PointClass({
  2876. value : value,
  2877. label : label,
  2878. x: pointPosition.x,
  2879. y: pointPosition.y,
  2880. strokeColor : this.datasets[datasetIndex].pointStrokeColor,
  2881. fillColor : this.datasets[datasetIndex].pointColor
  2882. }));
  2883. },this);
  2884. this.scale.labels.push(label);
  2885. this.reflow();
  2886. this.update();
  2887. },
  2888. removeData : function(){
  2889. this.scale.valuesCount--;
  2890. this.scale.labels.shift();
  2891. helpers.each(this.datasets,function(dataset){
  2892. dataset.points.shift();
  2893. },this);
  2894. this.reflow();
  2895. this.update();
  2896. },
  2897. update : function(){
  2898. this.eachPoints(function(point){
  2899. point.save();
  2900. });
  2901. this.reflow();
  2902. this.render();
  2903. },
  2904. reflow: function(){
  2905. helpers.extend(this.scale, {
  2906. width : this.chart.width,
  2907. height: this.chart.height,
  2908. size : helpers.min([this.chart.width, this.chart.height]),
  2909. xCenter: this.chart.width/2,
  2910. yCenter: this.chart.height/2
  2911. });
  2912. this.updateScaleRange(this.datasets);
  2913. this.scale.setScaleSize();
  2914. this.scale.buildYLabels();
  2915. },
  2916. draw : function(ease){
  2917. var easeDecimal = ease || 1,
  2918. ctx = this.chart.ctx;
  2919. this.clear();
  2920. this.scale.draw();
  2921. helpers.each(this.datasets,function(dataset){
  2922. //Transition each point first so that the line and point drawing isn't out of sync
  2923. helpers.each(dataset.points,function(point,index){
  2924. if (point.hasValue()){
  2925. point.transition(this.scale.getPointPosition(index, this.scale.calculateCenterOffset(point.value)), easeDecimal);
  2926. }
  2927. },this);
  2928. //Draw the line between all the points
  2929. ctx.lineWidth = this.options.datasetStrokeWidth;
  2930. ctx.strokeStyle = dataset.strokeColor;
  2931. ctx.beginPath();
  2932. helpers.each(dataset.points,function(point,index){
  2933. if (index === 0){
  2934. ctx.moveTo(point.x,point.y);
  2935. }
  2936. else{
  2937. ctx.lineTo(point.x,point.y);
  2938. }
  2939. },this);
  2940. ctx.closePath();
  2941. ctx.stroke();
  2942. ctx.fillStyle = dataset.fillColor;
  2943. ctx.fill();
  2944. //Now draw the points over the line
  2945. //A little inefficient double looping, but better than the line
  2946. //lagging behind the point positions
  2947. helpers.each(dataset.points,function(point){
  2948. if (point.hasValue()){
  2949. point.draw();
  2950. }
  2951. });
  2952. },this);
  2953. }
  2954. });
  2955. }).call(this);