chart-core.js 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943
  1. /*!
  2. * Chart.js
  3. * http://chartjs.org/
  4. * Version: {{ version }}
  5. *
  6. * Copyright 2014 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 width = this.width = context.canvas.width;
  22. var height = this.height = context.canvas.height;
  23. this.aspectRatio = this.width / this.height;
  24. //High pixel density displays - multiply the size of the canvas height/width by the device pixel ratio, then scale.
  25. helpers.retinaScale(this);
  26. return this;
  27. };
  28. //Globally expose the defaults to allow for user updating/changing
  29. Chart.defaults = {
  30. global: {
  31. // Boolean - Whether to animate the chart
  32. animation: true,
  33. // Number - Number of animation steps
  34. animationSteps: 60,
  35. // String - Animation easing effect
  36. animationEasing: "easeOutQuart",
  37. // Boolean - If we should show the scale at all
  38. showScale: true,
  39. // Boolean - If we want to override with a hard coded scale
  40. scaleOverride: false,
  41. // ** Required if scaleOverride is true **
  42. // Number - The number of steps in a hard coded scale
  43. scaleSteps: null,
  44. // Number - The value jump in the hard coded scale
  45. scaleStepWidth: null,
  46. // Number - The scale starting value
  47. scaleStartValue: null,
  48. // String - Colour of the scale line
  49. scaleLineColor: "rgba(0,0,0,.1)",
  50. // Number - Pixel width of the scale line
  51. scaleLineWidth: 1,
  52. // Boolean - Whether to show labels on the scale
  53. scaleShowLabels: true,
  54. // Interpolated JS string - can access value
  55. scaleLabel: "<%=value%>",
  56. // Boolean - Whether the scale should stick to integers, and not show any floats even if drawing space is there
  57. scaleIntegersOnly: true,
  58. // Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
  59. scaleBeginAtZero: false,
  60. // String - Scale label font declaration for the scale label
  61. scaleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
  62. // Number - Scale label font size in pixels
  63. scaleFontSize: 12,
  64. // String - Scale label font weight style
  65. scaleFontStyle: "normal",
  66. // String - Scale label font colour
  67. scaleFontColor: "#666",
  68. // Boolean - whether or not the chart should be responsive and resize when the browser does.
  69. responsive: false,
  70. // Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
  71. maintainAspectRatio: true,
  72. // Boolean - Determines whether to draw tooltips on the canvas or not - attaches events to touchmove & mousemove
  73. showTooltips: true,
  74. // Array - Array of string names to attach tooltip events
  75. tooltipEvents: ["mousemove", "touchstart", "touchmove", "mouseout"],
  76. // String - Tooltip background colour
  77. tooltipFillColor: "rgba(0,0,0,0.8)",
  78. // String - Tooltip label font declaration for the scale label
  79. tooltipFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
  80. // Number - Tooltip label font size in pixels
  81. tooltipFontSize: 14,
  82. // String - Tooltip font weight style
  83. tooltipFontStyle: "normal",
  84. // String - Tooltip label font colour
  85. tooltipFontColor: "#fff",
  86. // String - Tooltip title font declaration for the scale label
  87. tooltipTitleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
  88. // Number - Tooltip title font size in pixels
  89. tooltipTitleFontSize: 14,
  90. // String - Tooltip title font weight style
  91. tooltipTitleFontStyle: "bold",
  92. // String - Tooltip title font colour
  93. tooltipTitleFontColor: "#fff",
  94. // Number - pixel width of padding around tooltip text
  95. tooltipYPadding: 6,
  96. // Number - pixel width of padding around tooltip text
  97. tooltipXPadding: 6,
  98. // Number - Size of the caret on the tooltip
  99. tooltipCaretSize: 8,
  100. // Number - Pixel radius of the tooltip border
  101. tooltipCornerRadius: 6,
  102. // Number - Pixel offset from point x to tooltip edge
  103. tooltipXOffset: 10,
  104. // String - Template string for single tooltips
  105. tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>",
  106. // String - Template string for single tooltips
  107. multiTooltipTemplate: "<%= value %>",
  108. // String - Colour behind the legend colour block
  109. multiTooltipKeyBackground: '#fff',
  110. // Function - Will fire on animation progression.
  111. onAnimationProgress: function(){},
  112. // Function - Will fire on animation completion.
  113. onAnimationComplete: function(){}
  114. }
  115. };
  116. //Create a dictionary of chart types, to allow for extension of existing types
  117. Chart.types = {};
  118. //Global Chart helpers object for utility methods and classes
  119. var helpers = Chart.helpers = {};
  120. //-- Basic js utility methods
  121. var each = helpers.each = function(loopable,callback,self){
  122. var additionalArgs = Array.prototype.slice.call(arguments, 3);
  123. // Check to see if null or undefined firstly.
  124. if (loopable){
  125. if (loopable.length === +loopable.length){
  126. var i;
  127. for (i=0; i<loopable.length; i++){
  128. callback.apply(self,[loopable[i], i].concat(additionalArgs));
  129. }
  130. }
  131. else{
  132. for (var item in loopable){
  133. callback.apply(self,[loopable[item],item].concat(additionalArgs));
  134. }
  135. }
  136. }
  137. },
  138. clone = helpers.clone = function(obj){
  139. var objClone = {};
  140. each(obj,function(value,key){
  141. if (obj.hasOwnProperty(key)) objClone[key] = value;
  142. });
  143. return objClone;
  144. },
  145. extend = helpers.extend = function(base){
  146. each(Array.prototype.slice.call(arguments,1), function(extensionObject) {
  147. each(extensionObject,function(value,key){
  148. if (extensionObject.hasOwnProperty(key)) base[key] = value;
  149. });
  150. });
  151. return base;
  152. },
  153. merge = helpers.merge = function(base,master){
  154. //Merge properties in left object over to a shallow clone of object right.
  155. var args = Array.prototype.slice.call(arguments,0);
  156. args.unshift({});
  157. return extend.apply(null, args);
  158. },
  159. indexOf = helpers.indexOf = function(arrayToSearch, item){
  160. if (Array.prototype.indexOf) {
  161. return arrayToSearch.indexOf(item);
  162. }
  163. else{
  164. for (var i = 0; i < arrayToSearch.length; i++) {
  165. if (arrayToSearch[i] === item) return i;
  166. }
  167. return -1;
  168. }
  169. },
  170. where = helpers.where = function(collection, filterCallback){
  171. var filtered = [];
  172. helpers.each(collection, function(item){
  173. if (filterCallback(item)){
  174. filtered.push(item);
  175. }
  176. });
  177. return filtered;
  178. },
  179. findNextWhere = helpers.findNextWhere = function(arrayToSearch, filterCallback, startIndex){
  180. // Default to start of the array
  181. if (!startIndex){
  182. startIndex = -1;
  183. }
  184. for (var i = startIndex + 1; i < arrayToSearch.length; i++) {
  185. var currentItem = arrayToSearch[i];
  186. if (filterCallback(currentItem)){
  187. return currentItem;
  188. }
  189. };
  190. },
  191. findPreviousWhere = helpers.findPreviousWhere = function(arrayToSearch, filterCallback, startIndex){
  192. // Default to end of the array
  193. if (!startIndex){
  194. startIndex = arrayToSearch.length;
  195. }
  196. for (var i = startIndex - 1; i >= 0; i--) {
  197. var currentItem = arrayToSearch[i];
  198. if (filterCallback(currentItem)){
  199. return currentItem;
  200. }
  201. };
  202. },
  203. inherits = helpers.inherits = function(extensions){
  204. //Basic javascript inheritance based on the model created in Backbone.js
  205. var parent = this;
  206. var ChartElement = (extensions && extensions.hasOwnProperty("constructor")) ? extensions.constructor : function(){ return parent.apply(this, arguments); };
  207. var Surrogate = function(){ this.constructor = ChartElement;};
  208. Surrogate.prototype = parent.prototype;
  209. ChartElement.prototype = new Surrogate();
  210. ChartElement.extend = inherits;
  211. if (extensions) extend(ChartElement.prototype, extensions);
  212. ChartElement.__super__ = parent.prototype;
  213. return ChartElement;
  214. },
  215. noop = helpers.noop = function(){},
  216. uid = helpers.uid = (function(){
  217. var id=0;
  218. return function(){
  219. return "chart-" + id++;
  220. };
  221. })(),
  222. warn = helpers.warn = function(str){
  223. //Method for warning of errors
  224. if (window.console && typeof window.console.warn == "function") console.warn(str);
  225. },
  226. amd = helpers.amd = (typeof define == 'function' && define.amd),
  227. //-- Math methods
  228. isNumber = helpers.isNumber = function(n){
  229. return !isNaN(parseFloat(n)) && isFinite(n);
  230. },
  231. max = helpers.max = function(array){
  232. return Math.max.apply( Math, array );
  233. },
  234. min = helpers.min = function(array){
  235. return Math.min.apply( Math, array );
  236. },
  237. cap = helpers.cap = function(valueToCap,maxValue,minValue){
  238. if(isNumber(maxValue)) {
  239. if( valueToCap > maxValue ) {
  240. return maxValue;
  241. }
  242. }
  243. else if(isNumber(minValue)){
  244. if ( valueToCap < minValue ){
  245. return minValue;
  246. }
  247. }
  248. return valueToCap;
  249. },
  250. getDecimalPlaces = helpers.getDecimalPlaces = function(num){
  251. if (num%1!==0 && isNumber(num)){
  252. return num.toString().split(".")[1].length;
  253. }
  254. else {
  255. return 0;
  256. }
  257. },
  258. toRadians = helpers.radians = function(degrees){
  259. return degrees * (Math.PI/180);
  260. },
  261. // Gets the angle from vertical upright to the point about a centre.
  262. getAngleFromPoint = helpers.getAngleFromPoint = function(centrePoint, anglePoint){
  263. var distanceFromXCenter = anglePoint.x - centrePoint.x,
  264. distanceFromYCenter = anglePoint.y - centrePoint.y,
  265. radialDistanceFromCenter = Math.sqrt( distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
  266. var angle = Math.PI * 2 + Math.atan2(distanceFromYCenter, distanceFromXCenter);
  267. //If the segment is in the top left quadrant, we need to add another rotation to the angle
  268. if (distanceFromXCenter < 0 && distanceFromYCenter < 0){
  269. angle += Math.PI*2;
  270. }
  271. return {
  272. angle: angle,
  273. distance: radialDistanceFromCenter
  274. };
  275. },
  276. aliasPixel = helpers.aliasPixel = function(pixelWidth){
  277. return (pixelWidth % 2 === 0) ? 0 : 0.5;
  278. },
  279. splineCurve = helpers.splineCurve = function(FirstPoint,MiddlePoint,AfterPoint,t){
  280. //Props to Rob Spencer at scaled innovation for his post on splining between points
  281. //http://scaledinnovation.com/analytics/splines/aboutSplines.html
  282. var d01=Math.sqrt(Math.pow(MiddlePoint.x-FirstPoint.x,2)+Math.pow(MiddlePoint.y-FirstPoint.y,2)),
  283. d12=Math.sqrt(Math.pow(AfterPoint.x-MiddlePoint.x,2)+Math.pow(AfterPoint.y-MiddlePoint.y,2)),
  284. fa=t*d01/(d01+d12),// scaling factor for triangle Ta
  285. fb=t*d12/(d01+d12);
  286. return {
  287. inner : {
  288. x : MiddlePoint.x-fa*(AfterPoint.x-FirstPoint.x),
  289. y : MiddlePoint.y-fa*(AfterPoint.y-FirstPoint.y)
  290. },
  291. outer : {
  292. x: MiddlePoint.x+fb*(AfterPoint.x-FirstPoint.x),
  293. y : MiddlePoint.y+fb*(AfterPoint.y-FirstPoint.y)
  294. }
  295. };
  296. },
  297. calculateOrderOfMagnitude = helpers.calculateOrderOfMagnitude = function(val){
  298. return Math.floor(Math.log(val) / Math.LN10);
  299. },
  300. calculateScaleRange = helpers.calculateScaleRange = function(valuesArray, drawingSize, textSize, startFromZero, integersOnly){
  301. //Set a minimum step of two - a point at the top of the graph, and a point at the base
  302. var minSteps = 2,
  303. maxSteps = Math.floor(drawingSize/(textSize * 1.5)),
  304. skipFitting = (minSteps >= maxSteps);
  305. var maxValue = max(valuesArray),
  306. minValue = min(valuesArray);
  307. // We need some degree of seperation here to calculate the scales if all the values are the same
  308. // Adding/minusing 0.5 will give us a range of 1.
  309. if (maxValue === minValue){
  310. maxValue += 0.5;
  311. // So we don't end up with a graph with a negative start value if we've said always start from zero
  312. if (minValue >= 0.5 && !startFromZero){
  313. minValue -= 0.5;
  314. }
  315. else{
  316. // Make up a whole number above the values
  317. maxValue += 0.5;
  318. }
  319. }
  320. var valueRange = Math.abs(maxValue - minValue),
  321. rangeOrderOfMagnitude = calculateOrderOfMagnitude(valueRange),
  322. graphMax = Math.ceil(maxValue / (1 * Math.pow(10, rangeOrderOfMagnitude))) * Math.pow(10, rangeOrderOfMagnitude),
  323. graphMin = (startFromZero) ? 0 : Math.floor(minValue / (1 * Math.pow(10, rangeOrderOfMagnitude))) * Math.pow(10, rangeOrderOfMagnitude),
  324. graphRange = graphMax - graphMin,
  325. stepValue = Math.pow(10, rangeOrderOfMagnitude),
  326. numberOfSteps = Math.round(graphRange / stepValue);
  327. //If we have more space on the graph we'll use it to give more definition to the data
  328. while((numberOfSteps > maxSteps || (numberOfSteps * 2) < maxSteps) && !skipFitting) {
  329. if(numberOfSteps > maxSteps){
  330. stepValue *=2;
  331. numberOfSteps = Math.round(graphRange/stepValue);
  332. // Don't ever deal with a decimal number of steps - cancel fitting and just use the minimum number of steps.
  333. if (numberOfSteps % 1 !== 0){
  334. skipFitting = true;
  335. }
  336. }
  337. //We can fit in double the amount of scale points on the scale
  338. else{
  339. //If user has declared ints only, and the step value isn't a decimal
  340. if (integersOnly && rangeOrderOfMagnitude >= 0){
  341. //If the user has said integers only, we need to check that making the scale more granular wouldn't make it a float
  342. if(stepValue/2 % 1 === 0){
  343. stepValue /=2;
  344. numberOfSteps = Math.round(graphRange/stepValue);
  345. }
  346. //If it would make it a float break out of the loop
  347. else{
  348. break;
  349. }
  350. }
  351. //If the scale doesn't have to be an int, make the scale more granular anyway.
  352. else{
  353. stepValue /=2;
  354. numberOfSteps = Math.round(graphRange/stepValue);
  355. }
  356. }
  357. }
  358. if (skipFitting){
  359. numberOfSteps = minSteps;
  360. stepValue = graphRange / numberOfSteps;
  361. }
  362. return {
  363. steps : numberOfSteps,
  364. stepValue : stepValue,
  365. min : graphMin,
  366. max : graphMin + (numberOfSteps * stepValue)
  367. };
  368. },
  369. /* jshint ignore:start */
  370. // Blows up jshint errors based on the new Function constructor
  371. //Templating methods
  372. //Javascript micro templating by John Resig - source at http://ejohn.org/blog/javascript-micro-templating/
  373. template = helpers.template = function(templateString, valuesObject){
  374. // If templateString is function rather than string-template - call the function for valuesObject
  375. if(templateString instanceof Function){
  376. return templateString(valuesObject);
  377. }
  378. var cache = {};
  379. function tmpl(str, data){
  380. // Figure out if we're getting a template, or if we need to
  381. // load the template - and be sure to cache the result.
  382. var fn = !/\W/.test(str) ?
  383. cache[str] = cache[str] :
  384. // Generate a reusable function that will serve as a template
  385. // generator (and which will be cached).
  386. new Function("obj",
  387. "var p=[],print=function(){p.push.apply(p,arguments);};" +
  388. // Introduce the data as local variables using with(){}
  389. "with(obj){p.push('" +
  390. // Convert the template into pure JavaScript
  391. str
  392. .replace(/[\r\t\n]/g, " ")
  393. .split("<%").join("\t")
  394. .replace(/((^|%>)[^\t]*)'/g, "$1\r")
  395. .replace(/\t=(.*?)%>/g, "',$1,'")
  396. .split("\t").join("');")
  397. .split("%>").join("p.push('")
  398. .split("\r").join("\\'") +
  399. "');}return p.join('');"
  400. );
  401. // Provide some basic currying to the user
  402. return data ? fn( data ) : fn;
  403. }
  404. return tmpl(templateString,valuesObject);
  405. },
  406. /* jshint ignore:end */
  407. generateLabels = helpers.generateLabels = function(templateString,numberOfSteps,graphMin,stepValue){
  408. var labelsArray = new Array(numberOfSteps);
  409. if (labelTemplateString){
  410. each(labelsArray,function(val,index){
  411. labelsArray[index] = template(templateString,{value: (graphMin + (stepValue*(index+1)))});
  412. });
  413. }
  414. return labelsArray;
  415. },
  416. //--Animation methods
  417. //Easing functions adapted from Robert Penner's easing equations
  418. //http://www.robertpenner.com/easing/
  419. easingEffects = helpers.easingEffects = {
  420. linear: function (t) {
  421. return t;
  422. },
  423. easeInQuad: function (t) {
  424. return t * t;
  425. },
  426. easeOutQuad: function (t) {
  427. return -1 * t * (t - 2);
  428. },
  429. easeInOutQuad: function (t) {
  430. if ((t /= 1 / 2) < 1) return 1 / 2 * t * t;
  431. return -1 / 2 * ((--t) * (t - 2) - 1);
  432. },
  433. easeInCubic: function (t) {
  434. return t * t * t;
  435. },
  436. easeOutCubic: function (t) {
  437. return 1 * ((t = t / 1 - 1) * t * t + 1);
  438. },
  439. easeInOutCubic: function (t) {
  440. if ((t /= 1 / 2) < 1) return 1 / 2 * t * t * t;
  441. return 1 / 2 * ((t -= 2) * t * t + 2);
  442. },
  443. easeInQuart: function (t) {
  444. return t * t * t * t;
  445. },
  446. easeOutQuart: function (t) {
  447. return -1 * ((t = t / 1 - 1) * t * t * t - 1);
  448. },
  449. easeInOutQuart: function (t) {
  450. if ((t /= 1 / 2) < 1) return 1 / 2 * t * t * t * t;
  451. return -1 / 2 * ((t -= 2) * t * t * t - 2);
  452. },
  453. easeInQuint: function (t) {
  454. return 1 * (t /= 1) * t * t * t * t;
  455. },
  456. easeOutQuint: function (t) {
  457. return 1 * ((t = t / 1 - 1) * t * t * t * t + 1);
  458. },
  459. easeInOutQuint: function (t) {
  460. if ((t /= 1 / 2) < 1) return 1 / 2 * t * t * t * t * t;
  461. return 1 / 2 * ((t -= 2) * t * t * t * t + 2);
  462. },
  463. easeInSine: function (t) {
  464. return -1 * Math.cos(t / 1 * (Math.PI / 2)) + 1;
  465. },
  466. easeOutSine: function (t) {
  467. return 1 * Math.sin(t / 1 * (Math.PI / 2));
  468. },
  469. easeInOutSine: function (t) {
  470. return -1 / 2 * (Math.cos(Math.PI * t / 1) - 1);
  471. },
  472. easeInExpo: function (t) {
  473. return (t === 0) ? 1 : 1 * Math.pow(2, 10 * (t / 1 - 1));
  474. },
  475. easeOutExpo: function (t) {
  476. return (t === 1) ? 1 : 1 * (-Math.pow(2, -10 * t / 1) + 1);
  477. },
  478. easeInOutExpo: function (t) {
  479. if (t === 0) return 0;
  480. if (t === 1) return 1;
  481. if ((t /= 1 / 2) < 1) return 1 / 2 * Math.pow(2, 10 * (t - 1));
  482. return 1 / 2 * (-Math.pow(2, -10 * --t) + 2);
  483. },
  484. easeInCirc: function (t) {
  485. if (t >= 1) return t;
  486. return -1 * (Math.sqrt(1 - (t /= 1) * t) - 1);
  487. },
  488. easeOutCirc: function (t) {
  489. return 1 * Math.sqrt(1 - (t = t / 1 - 1) * t);
  490. },
  491. easeInOutCirc: function (t) {
  492. if ((t /= 1 / 2) < 1) return -1 / 2 * (Math.sqrt(1 - t * t) - 1);
  493. return 1 / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1);
  494. },
  495. easeInElastic: function (t) {
  496. var s = 1.70158;
  497. var p = 0;
  498. var a = 1;
  499. if (t === 0) return 0;
  500. if ((t /= 1) == 1) return 1;
  501. if (!p) p = 1 * 0.3;
  502. if (a < Math.abs(1)) {
  503. a = 1;
  504. s = p / 4;
  505. } else s = p / (2 * Math.PI) * Math.asin(1 / a);
  506. return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p));
  507. },
  508. easeOutElastic: function (t) {
  509. var s = 1.70158;
  510. var p = 0;
  511. var a = 1;
  512. if (t === 0) return 0;
  513. if ((t /= 1) == 1) return 1;
  514. if (!p) p = 1 * 0.3;
  515. if (a < Math.abs(1)) {
  516. a = 1;
  517. s = p / 4;
  518. } else s = p / (2 * Math.PI) * Math.asin(1 / a);
  519. return a * Math.pow(2, -10 * t) * Math.sin((t * 1 - s) * (2 * Math.PI) / p) + 1;
  520. },
  521. easeInOutElastic: function (t) {
  522. var s = 1.70158;
  523. var p = 0;
  524. var a = 1;
  525. if (t === 0) return 0;
  526. if ((t /= 1 / 2) == 2) return 1;
  527. if (!p) p = 1 * (0.3 * 1.5);
  528. if (a < Math.abs(1)) {
  529. a = 1;
  530. s = p / 4;
  531. } else s = p / (2 * Math.PI) * Math.asin(1 / a);
  532. if (t < 1) return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p));
  533. return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p) * 0.5 + 1;
  534. },
  535. easeInBack: function (t) {
  536. var s = 1.70158;
  537. return 1 * (t /= 1) * t * ((s + 1) * t - s);
  538. },
  539. easeOutBack: function (t) {
  540. var s = 1.70158;
  541. return 1 * ((t = t / 1 - 1) * t * ((s + 1) * t + s) + 1);
  542. },
  543. easeInOutBack: function (t) {
  544. var s = 1.70158;
  545. if ((t /= 1 / 2) < 1) return 1 / 2 * (t * t * (((s *= (1.525)) + 1) * t - s));
  546. return 1 / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
  547. },
  548. easeInBounce: function (t) {
  549. return 1 - easingEffects.easeOutBounce(1 - t);
  550. },
  551. easeOutBounce: function (t) {
  552. if ((t /= 1) < (1 / 2.75)) {
  553. return 1 * (7.5625 * t * t);
  554. } else if (t < (2 / 2.75)) {
  555. return 1 * (7.5625 * (t -= (1.5 / 2.75)) * t + 0.75);
  556. } else if (t < (2.5 / 2.75)) {
  557. return 1 * (7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375);
  558. } else {
  559. return 1 * (7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375);
  560. }
  561. },
  562. easeInOutBounce: function (t) {
  563. if (t < 1 / 2) return easingEffects.easeInBounce(t * 2) * 0.5;
  564. return easingEffects.easeOutBounce(t * 2 - 1) * 0.5 + 1 * 0.5;
  565. }
  566. },
  567. //Request animation polyfill - http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
  568. requestAnimFrame = helpers.requestAnimFrame = (function(){
  569. return window.requestAnimationFrame ||
  570. window.webkitRequestAnimationFrame ||
  571. window.mozRequestAnimationFrame ||
  572. window.oRequestAnimationFrame ||
  573. window.msRequestAnimationFrame ||
  574. function(callback) {
  575. return window.setTimeout(callback, 1000 / 60);
  576. };
  577. })(),
  578. cancelAnimFrame = helpers.cancelAnimFrame = (function(){
  579. return window.cancelAnimationFrame ||
  580. window.webkitCancelAnimationFrame ||
  581. window.mozCancelAnimationFrame ||
  582. window.oCancelAnimationFrame ||
  583. window.msCancelAnimationFrame ||
  584. function(callback) {
  585. return window.clearTimeout(callback, 1000 / 60);
  586. };
  587. })(),
  588. animationLoop = helpers.animationLoop = function(callback,totalSteps,easingString,onProgress,onComplete,chartInstance){
  589. var currentStep = 0,
  590. easingFunction = easingEffects[easingString] || easingEffects.linear;
  591. var animationFrame = function(){
  592. currentStep++;
  593. var stepDecimal = currentStep/totalSteps;
  594. var easeDecimal = easingFunction(stepDecimal);
  595. callback.call(chartInstance,easeDecimal,stepDecimal, currentStep);
  596. onProgress.call(chartInstance,easeDecimal,stepDecimal);
  597. if (currentStep < totalSteps){
  598. chartInstance.animationFrame = requestAnimFrame(animationFrame);
  599. } else{
  600. onComplete.apply(chartInstance);
  601. }
  602. };
  603. requestAnimFrame(animationFrame);
  604. },
  605. //-- DOM methods
  606. getRelativePosition = helpers.getRelativePosition = function(evt){
  607. var mouseX, mouseY;
  608. var e = evt.originalEvent || evt,
  609. canvas = evt.currentTarget || evt.srcElement,
  610. boundingRect = canvas.getBoundingClientRect();
  611. if (e.touches){
  612. mouseX = e.touches[0].clientX - boundingRect.left;
  613. mouseY = e.touches[0].clientY - boundingRect.top;
  614. }
  615. else{
  616. mouseX = e.clientX - boundingRect.left;
  617. mouseY = e.clientY - boundingRect.top;
  618. }
  619. return {
  620. x : mouseX,
  621. y : mouseY
  622. };
  623. },
  624. addEvent = helpers.addEvent = function(node,eventType,method){
  625. if (node.addEventListener){
  626. node.addEventListener(eventType,method);
  627. } else if (node.attachEvent){
  628. node.attachEvent("on"+eventType, method);
  629. } else {
  630. node["on"+eventType] = method;
  631. }
  632. },
  633. removeEvent = helpers.removeEvent = function(node, eventType, handler){
  634. if (node.removeEventListener){
  635. node.removeEventListener(eventType, handler, false);
  636. } else if (node.detachEvent){
  637. node.detachEvent("on"+eventType,handler);
  638. } else{
  639. node["on" + eventType] = noop;
  640. }
  641. },
  642. bindEvents = helpers.bindEvents = function(chartInstance, arrayOfEvents, handler){
  643. // Create the events object if it's not already present
  644. if (!chartInstance.events) chartInstance.events = {};
  645. each(arrayOfEvents,function(eventName){
  646. chartInstance.events[eventName] = function(){
  647. handler.apply(chartInstance, arguments);
  648. };
  649. addEvent(chartInstance.chart.canvas,eventName,chartInstance.events[eventName]);
  650. });
  651. },
  652. unbindEvents = helpers.unbindEvents = function (chartInstance, arrayOfEvents) {
  653. each(arrayOfEvents, function(handler,eventName){
  654. removeEvent(chartInstance.chart.canvas, eventName, handler);
  655. });
  656. },
  657. getMaximumWidth = helpers.getMaximumWidth = function(domNode){
  658. var container = domNode.parentNode;
  659. // TODO = check cross browser stuff with this.
  660. return container.clientWidth;
  661. },
  662. getMaximumHeight = helpers.getMaximumHeight = function(domNode){
  663. var container = domNode.parentNode;
  664. // TODO = check cross browser stuff with this.
  665. return container.clientHeight;
  666. },
  667. getMaximumSize = helpers.getMaximumSize = helpers.getMaximumWidth, // legacy support
  668. retinaScale = helpers.retinaScale = function(chart){
  669. var ctx = chart.ctx,
  670. width = chart.canvas.width,
  671. height = chart.canvas.height;
  672. if (window.devicePixelRatio) {
  673. ctx.canvas.style.width = width + "px";
  674. ctx.canvas.style.height = height + "px";
  675. ctx.canvas.height = height * window.devicePixelRatio;
  676. ctx.canvas.width = width * window.devicePixelRatio;
  677. ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
  678. }
  679. },
  680. //-- Canvas methods
  681. clear = helpers.clear = function(chart){
  682. chart.ctx.clearRect(0,0,chart.width,chart.height);
  683. },
  684. fontString = helpers.fontString = function(pixelSize,fontStyle,fontFamily){
  685. return fontStyle + " " + pixelSize+"px " + fontFamily;
  686. },
  687. longestText = helpers.longestText = function(ctx,font,arrayOfStrings){
  688. ctx.font = font;
  689. var longest = 0;
  690. each(arrayOfStrings,function(string){
  691. var textWidth = ctx.measureText(string).width;
  692. longest = (textWidth > longest) ? textWidth : longest;
  693. });
  694. return longest;
  695. },
  696. drawRoundedRectangle = helpers.drawRoundedRectangle = function(ctx,x,y,width,height,radius){
  697. ctx.beginPath();
  698. ctx.moveTo(x + radius, y);
  699. ctx.lineTo(x + width - radius, y);
  700. ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
  701. ctx.lineTo(x + width, y + height - radius);
  702. ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
  703. ctx.lineTo(x + radius, y + height);
  704. ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
  705. ctx.lineTo(x, y + radius);
  706. ctx.quadraticCurveTo(x, y, x + radius, y);
  707. ctx.closePath();
  708. };
  709. //Store a reference to each instance - allowing us to globally resize chart instances on window resize.
  710. //Destroy method on the chart will remove the instance of the chart from this reference.
  711. Chart.instances = {};
  712. Chart.Type = function(data,options,chart){
  713. this.options = options;
  714. this.chart = chart;
  715. this.id = uid();
  716. //Add the chart instance to the global namespace
  717. Chart.instances[this.id] = this;
  718. // Initialize is always called when a chart type is created
  719. // By default it is a no op, but it should be extended
  720. if (options.responsive){
  721. this.resize();
  722. }
  723. this.initialize.call(this,data);
  724. };
  725. //Core methods that'll be a part of every chart type
  726. extend(Chart.Type.prototype,{
  727. initialize : function(){return this;},
  728. clear : function(){
  729. clear(this.chart);
  730. return this;
  731. },
  732. stop : function(){
  733. // Stops any current animation loop occuring
  734. helpers.cancelAnimFrame.call(root, this.animationFrame);
  735. return this;
  736. },
  737. resize : function(callback){
  738. this.stop();
  739. var canvas = this.chart.canvas,
  740. newWidth = getMaximumWidth(this.chart.canvas),
  741. newHeight = this.options.maintainAspectRatio ? newWidth / this.chart.aspectRatio : getMaximumHeight(this.chart.canvas);
  742. canvas.width = this.chart.width = newWidth;
  743. canvas.height = this.chart.height = newHeight;
  744. retinaScale(this.chart);
  745. if (typeof callback === "function"){
  746. callback.apply(this, Array.prototype.slice.call(arguments, 1));
  747. }
  748. return this;
  749. },
  750. reflow : noop,
  751. render : function(reflow){
  752. if (reflow){
  753. this.reflow();
  754. }
  755. if (this.options.animation && !reflow){
  756. helpers.animationLoop(
  757. this.draw,
  758. this.options.animationSteps,
  759. this.options.animationEasing,
  760. this.options.onAnimationProgress,
  761. this.options.onAnimationComplete,
  762. this
  763. );
  764. }
  765. else{
  766. this.draw();
  767. this.options.onAnimationComplete.call(this);
  768. }
  769. return this;
  770. },
  771. generateLegend : function(){
  772. return template(this.options.legendTemplate,this);
  773. },
  774. destroy : function(){
  775. this.clear();
  776. unbindEvents(this, this.events);
  777. delete Chart.instances[this.id];
  778. },
  779. showTooltip : function(ChartElements, forceRedraw){
  780. // Only redraw the chart if we've actually changed what we're hovering on.
  781. if (typeof this.activeElements === 'undefined') this.activeElements = [];
  782. var isChanged = (function(Elements){
  783. var changed = false;
  784. if (Elements.length !== this.activeElements.length){
  785. changed = true;
  786. return changed;
  787. }
  788. each(Elements, function(element, index){
  789. if (element !== this.activeElements[index]){
  790. changed = true;
  791. }
  792. }, this);
  793. return changed;
  794. }).call(this, ChartElements);
  795. if (!isChanged && !forceRedraw){
  796. return;
  797. }
  798. else{
  799. this.activeElements = ChartElements;
  800. }
  801. this.draw();
  802. if (ChartElements.length > 0){
  803. // If we have multiple datasets, show a MultiTooltip for all of the data points at that index
  804. if (this.datasets && this.datasets.length > 1) {
  805. var dataArray,
  806. dataIndex;
  807. for (var i = this.datasets.length - 1; i >= 0; i--) {
  808. dataArray = this.datasets[i].points || this.datasets[i].bars || this.datasets[i].segments;
  809. dataIndex = indexOf(dataArray, ChartElements[0]);
  810. if (dataIndex !== -1){
  811. break;
  812. }
  813. }
  814. var tooltipLabels = [],
  815. tooltipColors = [],
  816. medianPosition = (function(index) {
  817. // Get all the points at that particular index
  818. var Elements = [],
  819. dataCollection,
  820. xPositions = [],
  821. yPositions = [],
  822. xMax,
  823. yMax,
  824. xMin,
  825. yMin;
  826. helpers.each(this.datasets, function(dataset){
  827. dataCollection = dataset.points || dataset.bars || dataset.segments;
  828. if (dataCollection[dataIndex] && dataCollection[dataIndex].hasValue()){
  829. Elements.push(dataCollection[dataIndex]);
  830. }
  831. });
  832. helpers.each(Elements, function(element) {
  833. xPositions.push(element.x);
  834. yPositions.push(element.y);
  835. //Include any colour information about the element
  836. tooltipLabels.push(helpers.template(this.options.multiTooltipTemplate, element));
  837. tooltipColors.push({
  838. fill: element._saved.fillColor || element.fillColor,
  839. stroke: element._saved.strokeColor || element.strokeColor
  840. });
  841. }, this);
  842. yMin = min(yPositions);
  843. yMax = max(yPositions);
  844. xMin = min(xPositions);
  845. xMax = max(xPositions);
  846. return {
  847. x: (xMin > this.chart.width/2) ? xMin : xMax,
  848. y: (yMin + yMax)/2
  849. };
  850. }).call(this, dataIndex);
  851. new Chart.MultiTooltip({
  852. x: medianPosition.x,
  853. y: medianPosition.y,
  854. xPadding: this.options.tooltipXPadding,
  855. yPadding: this.options.tooltipYPadding,
  856. xOffset: this.options.tooltipXOffset,
  857. fillColor: this.options.tooltipFillColor,
  858. textColor: this.options.tooltipFontColor,
  859. fontFamily: this.options.tooltipFontFamily,
  860. fontStyle: this.options.tooltipFontStyle,
  861. fontSize: this.options.tooltipFontSize,
  862. titleTextColor: this.options.tooltipTitleFontColor,
  863. titleFontFamily: this.options.tooltipTitleFontFamily,
  864. titleFontStyle: this.options.tooltipTitleFontStyle,
  865. titleFontSize: this.options.tooltipTitleFontSize,
  866. cornerRadius: this.options.tooltipCornerRadius,
  867. labels: tooltipLabels,
  868. legendColors: tooltipColors,
  869. legendColorBackground : this.options.multiTooltipKeyBackground,
  870. title: ChartElements[0].label,
  871. chart: this.chart,
  872. ctx: this.chart.ctx
  873. }).draw();
  874. } else {
  875. each(ChartElements, function(Element) {
  876. var tooltipPosition = Element.tooltipPosition();
  877. new Chart.Tooltip({
  878. x: Math.round(tooltipPosition.x),
  879. y: Math.round(tooltipPosition.y),
  880. xPadding: this.options.tooltipXPadding,
  881. yPadding: this.options.tooltipYPadding,
  882. fillColor: this.options.tooltipFillColor,
  883. textColor: this.options.tooltipFontColor,
  884. fontFamily: this.options.tooltipFontFamily,
  885. fontStyle: this.options.tooltipFontStyle,
  886. fontSize: this.options.tooltipFontSize,
  887. caretHeight: this.options.tooltipCaretSize,
  888. cornerRadius: this.options.tooltipCornerRadius,
  889. text: template(this.options.tooltipTemplate, Element),
  890. chart: this.chart
  891. }).draw();
  892. }, this);
  893. }
  894. }
  895. return this;
  896. },
  897. toBase64Image : function(){
  898. return this.chart.canvas.toDataURL.apply(this.chart.canvas, arguments);
  899. }
  900. });
  901. Chart.Type.extend = function(extensions){
  902. var parent = this;
  903. var ChartType = function(){
  904. return parent.apply(this,arguments);
  905. };
  906. //Copy the prototype object of the this class
  907. ChartType.prototype = clone(parent.prototype);
  908. //Now overwrite some of the properties in the base class with the new extensions
  909. extend(ChartType.prototype, extensions);
  910. ChartType.extend = Chart.Type.extend;
  911. if (extensions.name || parent.prototype.name){
  912. var chartName = extensions.name || parent.prototype.name;
  913. //Assign any potential default values of the new chart type
  914. //If none are defined, we'll use a clone of the chart type this is being extended from.
  915. //I.e. if we extend a line chart, we'll use the defaults from the line chart if our new chart
  916. //doesn't define some defaults of their own.
  917. var baseDefaults = (Chart.defaults[parent.prototype.name]) ? clone(Chart.defaults[parent.prototype.name]) : {};
  918. Chart.defaults[chartName] = extend(baseDefaults,extensions.defaults);
  919. Chart.types[chartName] = ChartType;
  920. //Register this new chart type in the Chart prototype
  921. Chart.prototype[chartName] = function(data,options){
  922. var config = merge(Chart.defaults.global, Chart.defaults[chartName], options || {});
  923. return new ChartType(data,config,this);
  924. };
  925. } else{
  926. warn("Name not provided for this chart, so it hasn't been registered");
  927. }
  928. return parent;
  929. };
  930. Chart.Element = function(configuration){
  931. extend(this,configuration);
  932. this.initialize.apply(this,arguments);
  933. this.save();
  934. };
  935. extend(Chart.Element.prototype,{
  936. initialize : function(){},
  937. restore : function(props){
  938. if (!props){
  939. extend(this,this._saved);
  940. } else {
  941. each(props,function(key){
  942. this[key] = this._saved[key];
  943. },this);
  944. }
  945. return this;
  946. },
  947. save : function(){
  948. this._saved = clone(this);
  949. delete this._saved._saved;
  950. return this;
  951. },
  952. update : function(newProps){
  953. each(newProps,function(value,key){
  954. this._saved[key] = this[key];
  955. this[key] = value;
  956. },this);
  957. return this;
  958. },
  959. transition : function(props,ease){
  960. each(props,function(value,key){
  961. this[key] = ((value - this._saved[key]) * ease) + this._saved[key];
  962. },this);
  963. return this;
  964. },
  965. tooltipPosition : function(){
  966. return {
  967. x : this.x,
  968. y : this.y
  969. };
  970. },
  971. hasValue: function(){
  972. return isNumber(this.value);
  973. }
  974. });
  975. Chart.Element.extend = inherits;
  976. Chart.Point = Chart.Element.extend({
  977. display: true,
  978. inRange: function(chartX,chartY){
  979. var hitDetectionRange = this.hitDetectionRadius + this.radius;
  980. return ((Math.pow(chartX-this.x, 2)+Math.pow(chartY-this.y, 2)) < Math.pow(hitDetectionRange,2));
  981. },
  982. draw : function(){
  983. if (this.display){
  984. var ctx = this.ctx;
  985. ctx.beginPath();
  986. ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2);
  987. ctx.closePath();
  988. ctx.strokeStyle = this.strokeColor;
  989. ctx.lineWidth = this.strokeWidth;
  990. ctx.fillStyle = this.fillColor;
  991. ctx.fill();
  992. ctx.stroke();
  993. }
  994. //Quick debug for bezier curve splining
  995. //Highlights control points and the line between them.
  996. //Handy for dev - stripped in the min version.
  997. // ctx.save();
  998. // ctx.fillStyle = "black";
  999. // ctx.strokeStyle = "black"
  1000. // ctx.beginPath();
  1001. // ctx.arc(this.controlPoints.inner.x,this.controlPoints.inner.y, 2, 0, Math.PI*2);
  1002. // ctx.fill();
  1003. // ctx.beginPath();
  1004. // ctx.arc(this.controlPoints.outer.x,this.controlPoints.outer.y, 2, 0, Math.PI*2);
  1005. // ctx.fill();
  1006. // ctx.moveTo(this.controlPoints.inner.x,this.controlPoints.inner.y);
  1007. // ctx.lineTo(this.x, this.y);
  1008. // ctx.lineTo(this.controlPoints.outer.x,this.controlPoints.outer.y);
  1009. // ctx.stroke();
  1010. // ctx.restore();
  1011. }
  1012. });
  1013. Chart.Arc = Chart.Element.extend({
  1014. inRange : function(chartX,chartY){
  1015. var pointRelativePosition = helpers.getAngleFromPoint(this, {
  1016. x: chartX,
  1017. y: chartY
  1018. });
  1019. //Check if within the range of the open/close angle
  1020. var betweenAngles = (pointRelativePosition.angle >= this.startAngle && pointRelativePosition.angle <= this.endAngle),
  1021. withinRadius = (pointRelativePosition.distance >= this.innerRadius && pointRelativePosition.distance <= this.outerRadius);
  1022. return (betweenAngles && withinRadius);
  1023. //Ensure within the outside of the arc centre, but inside arc outer
  1024. },
  1025. tooltipPosition : function(){
  1026. var centreAngle = this.startAngle + ((this.endAngle - this.startAngle) / 2),
  1027. rangeFromCentre = (this.outerRadius - this.innerRadius) / 2 + this.innerRadius;
  1028. return {
  1029. x : this.x + (Math.cos(centreAngle) * rangeFromCentre),
  1030. y : this.y + (Math.sin(centreAngle) * rangeFromCentre)
  1031. };
  1032. },
  1033. draw : function(animationPercent){
  1034. var easingDecimal = animationPercent || 1;
  1035. var ctx = this.ctx;
  1036. ctx.beginPath();
  1037. ctx.arc(this.x, this.y, this.outerRadius, this.startAngle, this.endAngle);
  1038. ctx.arc(this.x, this.y, this.innerRadius, this.endAngle, this.startAngle, true);
  1039. ctx.closePath();
  1040. ctx.strokeStyle = this.strokeColor;
  1041. ctx.lineWidth = this.strokeWidth;
  1042. ctx.fillStyle = this.fillColor;
  1043. ctx.fill();
  1044. ctx.lineJoin = 'bevel';
  1045. if (this.showStroke){
  1046. ctx.stroke();
  1047. }
  1048. }
  1049. });
  1050. Chart.Rectangle = Chart.Element.extend({
  1051. draw : function(){
  1052. var ctx = this.ctx,
  1053. halfWidth = this.width/2,
  1054. leftX = this.x - halfWidth,
  1055. rightX = this.x + halfWidth,
  1056. top = this.base - (this.base - this.y),
  1057. halfStroke = this.strokeWidth / 2;
  1058. // Canvas doesn't allow us to stroke inside the width so we can
  1059. // adjust the sizes to fit if we're setting a stroke on the line
  1060. if (this.showStroke){
  1061. leftX += halfStroke;
  1062. rightX -= halfStroke;
  1063. top += halfStroke;
  1064. }
  1065. ctx.beginPath();
  1066. ctx.fillStyle = this.fillColor;
  1067. ctx.strokeStyle = this.strokeColor;
  1068. ctx.lineWidth = this.strokeWidth;
  1069. // It'd be nice to keep this class totally generic to any rectangle
  1070. // and simply specify which border to miss out.
  1071. ctx.moveTo(leftX, this.base);
  1072. ctx.lineTo(leftX, top);
  1073. ctx.lineTo(rightX, top);
  1074. ctx.lineTo(rightX, this.base);
  1075. ctx.fill();
  1076. if (this.showStroke){
  1077. ctx.stroke();
  1078. }
  1079. },
  1080. height : function(){
  1081. return this.base - this.y;
  1082. },
  1083. inRange : function(chartX,chartY){
  1084. return (chartX >= this.x - this.width/2 && chartX <= this.x + this.width/2) && (chartY >= this.y && chartY <= this.base);
  1085. }
  1086. });
  1087. Chart.Tooltip = Chart.Element.extend({
  1088. draw : function(){
  1089. var ctx = this.chart.ctx;
  1090. ctx.font = fontString(this.fontSize,this.fontStyle,this.fontFamily);
  1091. this.xAlign = "center";
  1092. this.yAlign = "above";
  1093. //Distance between the actual element.y position and the start of the tooltip caret
  1094. var caretPadding = 2;
  1095. var tooltipWidth = ctx.measureText(this.text).width + 2*this.xPadding,
  1096. tooltipRectHeight = this.fontSize + 2*this.yPadding,
  1097. tooltipHeight = tooltipRectHeight + this.caretHeight + caretPadding;
  1098. if (this.x + tooltipWidth/2 >this.chart.width){
  1099. this.xAlign = "left";
  1100. } else if (this.x - tooltipWidth/2 < 0){
  1101. this.xAlign = "right";
  1102. }
  1103. if (this.y - tooltipHeight < 0){
  1104. this.yAlign = "below";
  1105. }
  1106. var tooltipX = this.x - tooltipWidth/2,
  1107. tooltipY = this.y - tooltipHeight;
  1108. ctx.fillStyle = this.fillColor;
  1109. switch(this.yAlign)
  1110. {
  1111. case "above":
  1112. //Draw a caret above the x/y
  1113. ctx.beginPath();
  1114. ctx.moveTo(this.x,this.y - caretPadding);
  1115. ctx.lineTo(this.x + this.caretHeight, this.y - (caretPadding + this.caretHeight));
  1116. ctx.lineTo(this.x - this.caretHeight, this.y - (caretPadding + this.caretHeight));
  1117. ctx.closePath();
  1118. ctx.fill();
  1119. break;
  1120. case "below":
  1121. tooltipY = this.y + caretPadding + this.caretHeight;
  1122. //Draw a caret below the x/y
  1123. ctx.beginPath();
  1124. ctx.moveTo(this.x, this.y + caretPadding);
  1125. ctx.lineTo(this.x + this.caretHeight, this.y + caretPadding + this.caretHeight);
  1126. ctx.lineTo(this.x - this.caretHeight, this.y + caretPadding + this.caretHeight);
  1127. ctx.closePath();
  1128. ctx.fill();
  1129. break;
  1130. }
  1131. switch(this.xAlign)
  1132. {
  1133. case "left":
  1134. tooltipX = this.x - tooltipWidth + (this.cornerRadius + this.caretHeight);
  1135. break;
  1136. case "right":
  1137. tooltipX = this.x - (this.cornerRadius + this.caretHeight);
  1138. break;
  1139. }
  1140. drawRoundedRectangle(ctx,tooltipX,tooltipY,tooltipWidth,tooltipRectHeight,this.cornerRadius);
  1141. ctx.fill();
  1142. ctx.fillStyle = this.textColor;
  1143. ctx.textAlign = "center";
  1144. ctx.textBaseline = "middle";
  1145. ctx.fillText(this.text, tooltipX + tooltipWidth/2, tooltipY + tooltipRectHeight/2);
  1146. }
  1147. });
  1148. Chart.MultiTooltip = Chart.Element.extend({
  1149. initialize : function(){
  1150. this.font = fontString(this.fontSize,this.fontStyle,this.fontFamily);
  1151. this.titleFont = fontString(this.titleFontSize,this.titleFontStyle,this.titleFontFamily);
  1152. this.height = (this.labels.length * this.fontSize) + ((this.labels.length-1) * (this.fontSize/2)) + (this.yPadding*2) + this.titleFontSize *1.5;
  1153. this.ctx.font = this.titleFont;
  1154. var titleWidth = this.ctx.measureText(this.title).width,
  1155. //Label has a legend square as well so account for this.
  1156. labelWidth = longestText(this.ctx,this.font,this.labels) + this.fontSize + 3,
  1157. longestTextWidth = max([labelWidth,titleWidth]);
  1158. this.width = longestTextWidth + (this.xPadding*2);
  1159. var halfHeight = this.height/2;
  1160. //Check to ensure the height will fit on the canvas
  1161. //The three is to buffer form the very
  1162. if (this.y - halfHeight < 0 ){
  1163. this.y = halfHeight;
  1164. } else if (this.y + halfHeight > this.chart.height){
  1165. this.y = this.chart.height - halfHeight;
  1166. }
  1167. //Decide whether to align left or right based on position on canvas
  1168. if (this.x > this.chart.width/2){
  1169. this.x -= this.xOffset + this.width;
  1170. } else {
  1171. this.x += this.xOffset;
  1172. }
  1173. },
  1174. getLineHeight : function(index){
  1175. var baseLineHeight = this.y - (this.height/2) + this.yPadding,
  1176. afterTitleIndex = index-1;
  1177. //If the index is zero, we're getting the title
  1178. if (index === 0){
  1179. return baseLineHeight + this.titleFontSize/2;
  1180. } else{
  1181. return baseLineHeight + ((this.fontSize*1.5*afterTitleIndex) + this.fontSize/2) + this.titleFontSize * 1.5;
  1182. }
  1183. },
  1184. draw : function(){
  1185. drawRoundedRectangle(this.ctx,this.x,this.y - this.height/2,this.width,this.height,this.cornerRadius);
  1186. var ctx = this.ctx;
  1187. ctx.fillStyle = this.fillColor;
  1188. ctx.fill();
  1189. ctx.closePath();
  1190. ctx.textAlign = "left";
  1191. ctx.textBaseline = "middle";
  1192. ctx.fillStyle = this.titleTextColor;
  1193. ctx.font = this.titleFont;
  1194. ctx.fillText(this.title,this.x + this.xPadding, this.getLineHeight(0));
  1195. ctx.font = this.font;
  1196. helpers.each(this.labels,function(label,index){
  1197. ctx.fillStyle = this.textColor;
  1198. ctx.fillText(label,this.x + this.xPadding + this.fontSize + 3, this.getLineHeight(index + 1));
  1199. //A bit gnarly, but clearing this rectangle breaks when using explorercanvas (clears whole canvas)
  1200. //ctx.clearRect(this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize/2, this.fontSize, this.fontSize);
  1201. //Instead we'll make a white filled block to put the legendColour palette over.
  1202. ctx.fillStyle = this.legendColorBackground;
  1203. ctx.fillRect(this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize/2, this.fontSize, this.fontSize);
  1204. ctx.fillStyle = this.legendColors[index].fill;
  1205. ctx.fillRect(this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize/2, this.fontSize, this.fontSize);
  1206. },this);
  1207. }
  1208. });
  1209. Chart.Scale = Chart.Element.extend({
  1210. initialize : function(){
  1211. this.fit();
  1212. },
  1213. buildYLabels : function(){
  1214. this.yLabels = [];
  1215. var stepDecimalPlaces = getDecimalPlaces(this.stepValue);
  1216. for (var i=0; i<=this.steps; i++){
  1217. this.yLabels.push(template(this.templateString,{value:(this.min + (i * this.stepValue)).toFixed(stepDecimalPlaces)}));
  1218. }
  1219. this.yLabelWidth = (this.display && this.showLabels) ? longestText(this.ctx,this.font,this.yLabels) : 0;
  1220. },
  1221. addXLabel : function(label){
  1222. this.xLabels.push(label);
  1223. this.valuesCount++;
  1224. this.fit();
  1225. },
  1226. removeXLabel : function(){
  1227. this.xLabels.shift();
  1228. this.valuesCount--;
  1229. this.fit();
  1230. },
  1231. // Fitting loop to rotate x Labels and figure out what fits there, and also calculate how many Y steps to use
  1232. fit: function(){
  1233. // First we need the width of the yLabels, assuming the xLabels aren't rotated
  1234. // To do that we need the base line at the top and base of the chart, assuming there is no x label rotation
  1235. this.startPoint = (this.display) ? this.fontSize : 0;
  1236. this.endPoint = (this.display) ? this.height - (this.fontSize * 1.5) - 5 : this.height; // -5 to pad labels
  1237. // Apply padding settings to the start and end point.
  1238. this.startPoint += this.padding;
  1239. this.endPoint -= this.padding;
  1240. // Cache the starting height, so can determine if we need to recalculate the scale yAxis
  1241. var cachedHeight = this.endPoint - this.startPoint,
  1242. cachedYLabelWidth;
  1243. // Build the current yLabels so we have an idea of what size they'll be to start
  1244. /*
  1245. * This sets what is returned from calculateScaleRange as static properties of this class:
  1246. *
  1247. this.steps;
  1248. this.stepValue;
  1249. this.min;
  1250. this.max;
  1251. *
  1252. */
  1253. this.calculateYRange(cachedHeight);
  1254. // With these properties set we can now build the array of yLabels
  1255. // and also the width of the largest yLabel
  1256. this.buildYLabels();
  1257. this.calculateXLabelRotation();
  1258. while((cachedHeight > this.endPoint - this.startPoint)){
  1259. cachedHeight = this.endPoint - this.startPoint;
  1260. cachedYLabelWidth = this.yLabelWidth;
  1261. this.calculateYRange(cachedHeight);
  1262. this.buildYLabels();
  1263. // Only go through the xLabel loop again if the yLabel width has changed
  1264. if (cachedYLabelWidth < this.yLabelWidth){
  1265. this.calculateXLabelRotation();
  1266. }
  1267. }
  1268. },
  1269. calculateXLabelRotation : function(){
  1270. //Get the width of each grid by calculating the difference
  1271. //between x offsets between 0 and 1.
  1272. this.ctx.font = this.font;
  1273. var firstWidth = this.ctx.measureText(this.xLabels[0]).width,
  1274. lastWidth = this.ctx.measureText(this.xLabels[this.xLabels.length - 1]).width,
  1275. firstRotated,
  1276. lastRotated;
  1277. this.xScalePaddingRight = lastWidth/2 + 3;
  1278. this.xScalePaddingLeft = (firstWidth/2 > this.yLabelWidth + 10) ? firstWidth/2 : this.yLabelWidth + 10;
  1279. this.xLabelRotation = 0;
  1280. if (this.display){
  1281. var originalLabelWidth = longestText(this.ctx,this.font,this.xLabels),
  1282. cosRotation,
  1283. firstRotatedWidth;
  1284. this.xLabelWidth = originalLabelWidth;
  1285. //Allow 3 pixels x2 padding either side for label readability
  1286. var xGridWidth = Math.floor(this.calculateX(1) - this.calculateX(0)) - 6;
  1287. //Max label rotate should be 90 - also act as a loop counter
  1288. while ((this.xLabelWidth > xGridWidth && this.xLabelRotation === 0) || (this.xLabelWidth > xGridWidth && this.xLabelRotation <= 90 && this.xLabelRotation > 0)){
  1289. cosRotation = Math.cos(toRadians(this.xLabelRotation));
  1290. firstRotated = cosRotation * firstWidth;
  1291. lastRotated = cosRotation * lastWidth;
  1292. // We're right aligning the text now.
  1293. if (firstRotated + this.fontSize / 2 > this.yLabelWidth + 8){
  1294. this.xScalePaddingLeft = firstRotated + this.fontSize / 2;
  1295. }
  1296. this.xScalePaddingRight = this.fontSize/2;
  1297. this.xLabelRotation++;
  1298. this.xLabelWidth = cosRotation * originalLabelWidth;
  1299. }
  1300. if (this.xLabelRotation > 0){
  1301. this.endPoint -= Math.sin(toRadians(this.xLabelRotation))*originalLabelWidth + 3;
  1302. }
  1303. }
  1304. else{
  1305. this.xLabelWidth = 0;
  1306. this.xScalePaddingRight = this.padding;
  1307. this.xScalePaddingLeft = this.padding;
  1308. }
  1309. },
  1310. // Needs to be overidden in each Chart type
  1311. // Otherwise we need to pass all the data into the scale class
  1312. calculateYRange: noop,
  1313. drawingArea: function(){
  1314. return this.startPoint - this.endPoint;
  1315. },
  1316. calculateY : function(value){
  1317. var scalingFactor = this.drawingArea() / (this.min - this.max);
  1318. return this.endPoint - (scalingFactor * (value - this.min));
  1319. },
  1320. calculateX : function(index){
  1321. var isRotated = (this.xLabelRotation > 0),
  1322. // innerWidth = (this.offsetGridLines) ? this.width - offsetLeft - this.padding : this.width - (offsetLeft + halfLabelWidth * 2) - this.padding,
  1323. innerWidth = this.width - (this.xScalePaddingLeft + this.xScalePaddingRight),
  1324. valueWidth = innerWidth/(this.valuesCount - ((this.offsetGridLines) ? 0 : 1)),
  1325. valueOffset = (valueWidth * index) + this.xScalePaddingLeft;
  1326. if (this.offsetGridLines){
  1327. valueOffset += (valueWidth/2);
  1328. }
  1329. return Math.round(valueOffset);
  1330. },
  1331. update : function(newProps){
  1332. helpers.extend(this, newProps);
  1333. this.fit();
  1334. },
  1335. draw : function(){
  1336. var ctx = this.ctx,
  1337. yLabelGap = (this.endPoint - this.startPoint) / this.steps,
  1338. xStart = Math.round(this.xScalePaddingLeft);
  1339. if (this.display){
  1340. ctx.fillStyle = this.textColor;
  1341. ctx.font = this.font;
  1342. each(this.yLabels,function(labelString,index){
  1343. var yLabelCenter = this.endPoint - (yLabelGap * index),
  1344. linePositionY = Math.round(yLabelCenter);
  1345. ctx.textAlign = "right";
  1346. ctx.textBaseline = "middle";
  1347. if (this.showLabels){
  1348. ctx.fillText(labelString,xStart - 10,yLabelCenter);
  1349. }
  1350. ctx.beginPath();
  1351. if (index > 0){
  1352. // This is a grid line in the centre, so drop that
  1353. ctx.lineWidth = this.gridLineWidth;
  1354. ctx.strokeStyle = this.gridLineColor;
  1355. } else {
  1356. // This is the first line on the scale
  1357. ctx.lineWidth = this.lineWidth;
  1358. ctx.strokeStyle = this.lineColor;
  1359. }
  1360. linePositionY += helpers.aliasPixel(ctx.lineWidth);
  1361. ctx.moveTo(xStart, linePositionY);
  1362. ctx.lineTo(this.width, linePositionY);
  1363. ctx.stroke();
  1364. ctx.closePath();
  1365. ctx.lineWidth = this.lineWidth;
  1366. ctx.strokeStyle = this.lineColor;
  1367. ctx.beginPath();
  1368. ctx.moveTo(xStart - 5, linePositionY);
  1369. ctx.lineTo(xStart, linePositionY);
  1370. ctx.stroke();
  1371. ctx.closePath();
  1372. },this);
  1373. each(this.xLabels,function(label,index){
  1374. var xPos = this.calculateX(index) + aliasPixel(this.lineWidth),
  1375. // Check to see if line/bar here and decide where to place the line
  1376. linePos = this.calculateX(index - (this.offsetGridLines ? 0.5 : 0)) + aliasPixel(this.lineWidth),
  1377. isRotated = (this.xLabelRotation > 0);
  1378. ctx.beginPath();
  1379. if (index > 0){
  1380. // This is a grid line in the centre, so drop that
  1381. ctx.lineWidth = this.gridLineWidth;
  1382. ctx.strokeStyle = this.gridLineColor;
  1383. } else {
  1384. // This is the first line on the scale
  1385. ctx.lineWidth = this.lineWidth;
  1386. ctx.strokeStyle = this.lineColor;
  1387. }
  1388. ctx.moveTo(linePos,this.endPoint);
  1389. ctx.lineTo(linePos,this.startPoint - 3);
  1390. ctx.stroke();
  1391. ctx.closePath();
  1392. ctx.lineWidth = this.lineWidth;
  1393. ctx.strokeStyle = this.lineColor;
  1394. // Small lines at the bottom of the base grid line
  1395. ctx.beginPath();
  1396. ctx.moveTo(linePos,this.endPoint);
  1397. ctx.lineTo(linePos,this.endPoint + 5);
  1398. ctx.stroke();
  1399. ctx.closePath();
  1400. ctx.save();
  1401. ctx.translate(xPos,(isRotated) ? this.endPoint + 12 : this.endPoint + 8);
  1402. ctx.rotate(toRadians(this.xLabelRotation)*-1);
  1403. ctx.font = this.font;
  1404. ctx.textAlign = (isRotated) ? "right" : "center";
  1405. ctx.textBaseline = (isRotated) ? "middle" : "top";
  1406. ctx.fillText(label, 0, 0);
  1407. ctx.restore();
  1408. },this);
  1409. }
  1410. }
  1411. });
  1412. Chart.RadialScale = Chart.Element.extend({
  1413. initialize: function(){
  1414. this.size = min([this.height, this.width]);
  1415. this.drawingArea = (this.display) ? (this.size/2) - (this.fontSize/2 + this.backdropPaddingY) : (this.size/2);
  1416. },
  1417. calculateCenterOffset: function(value){
  1418. // Take into account half font size + the yPadding of the top value
  1419. var scalingFactor = this.drawingArea / (this.max - this.min);
  1420. return (value - this.min) * scalingFactor;
  1421. },
  1422. update : function(){
  1423. if (!this.lineArc){
  1424. this.setScaleSize();
  1425. } else {
  1426. this.drawingArea = (this.display) ? (this.size/2) - (this.fontSize/2 + this.backdropPaddingY) : (this.size/2);
  1427. }
  1428. this.buildYLabels();
  1429. },
  1430. buildYLabels: function(){
  1431. this.yLabels = [];
  1432. var stepDecimalPlaces = getDecimalPlaces(this.stepValue);
  1433. for (var i=0; i<=this.steps; i++){
  1434. this.yLabels.push(template(this.templateString,{value:(this.min + (i * this.stepValue)).toFixed(stepDecimalPlaces)}));
  1435. }
  1436. },
  1437. getCircumference : function(){
  1438. return ((Math.PI*2) / this.valuesCount);
  1439. },
  1440. setScaleSize: function(){
  1441. /*
  1442. * Right, this is really confusing and there is a lot of maths going on here
  1443. * The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9
  1444. *
  1445. * Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif
  1446. *
  1447. * Solution:
  1448. *
  1449. * We assume the radius of the polygon is half the size of the canvas at first
  1450. * at each index we check if the text overlaps.
  1451. *
  1452. * Where it does, we store that angle and that index.
  1453. *
  1454. * After finding the largest index and angle we calculate how much we need to remove
  1455. * from the shape radius to move the point inwards by that x.
  1456. *
  1457. * We average the left and right distances to get the maximum shape radius that can fit in the box
  1458. * along with labels.
  1459. *
  1460. * Once we have that, we can find the centre point for the chart, by taking the x text protrusion
  1461. * on each side, removing that from the size, halving it and adding the left x protrusion width.
  1462. *
  1463. * This will mean we have a shape fitted to the canvas, as large as it can be with the labels
  1464. * and position it in the most space efficient manner
  1465. *
  1466. * https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif
  1467. */
  1468. // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.
  1469. // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points
  1470. var largestPossibleRadius = min([(this.height/2 - this.pointLabelFontSize - 5), this.width/2]),
  1471. pointPosition,
  1472. i,
  1473. textWidth,
  1474. halfTextWidth,
  1475. furthestRight = this.width,
  1476. furthestRightIndex,
  1477. furthestRightAngle,
  1478. furthestLeft = 0,
  1479. furthestLeftIndex,
  1480. furthestLeftAngle,
  1481. xProtrusionLeft,
  1482. xProtrusionRight,
  1483. radiusReductionRight,
  1484. radiusReductionLeft,
  1485. maxWidthRadius;
  1486. this.ctx.font = fontString(this.pointLabelFontSize,this.pointLabelFontStyle,this.pointLabelFontFamily);
  1487. for (i=0;i<this.valuesCount;i++){
  1488. // 5px to space the text slightly out - similar to what we do in the draw function.
  1489. pointPosition = this.getPointPosition(i, largestPossibleRadius);
  1490. textWidth = this.ctx.measureText(template(this.templateString, { value: this.labels[i] })).width + 5;
  1491. if (i === 0 || i === this.valuesCount/2){
  1492. // If we're at index zero, or exactly the middle, we're at exactly the top/bottom
  1493. // of the radar chart, so text will be aligned centrally, so we'll half it and compare
  1494. // w/left and right text sizes
  1495. halfTextWidth = textWidth/2;
  1496. if (pointPosition.x + halfTextWidth > furthestRight) {
  1497. furthestRight = pointPosition.x + halfTextWidth;
  1498. furthestRightIndex = i;
  1499. }
  1500. if (pointPosition.x - halfTextWidth < furthestLeft) {
  1501. furthestLeft = pointPosition.x - halfTextWidth;
  1502. furthestLeftIndex = i;
  1503. }
  1504. }
  1505. else if (i < this.valuesCount/2) {
  1506. // Less than half the values means we'll left align the text
  1507. if (pointPosition.x + textWidth > furthestRight) {
  1508. furthestRight = pointPosition.x + textWidth;
  1509. furthestRightIndex = i;
  1510. }
  1511. }
  1512. else if (i > this.valuesCount/2){
  1513. // More than half the values means we'll right align the text
  1514. if (pointPosition.x - textWidth < furthestLeft) {
  1515. furthestLeft = pointPosition.x - textWidth;
  1516. furthestLeftIndex = i;
  1517. }
  1518. }
  1519. }
  1520. xProtrusionLeft = furthestLeft;
  1521. xProtrusionRight = Math.ceil(furthestRight - this.width);
  1522. furthestRightAngle = this.getIndexAngle(furthestRightIndex);
  1523. furthestLeftAngle = this.getIndexAngle(furthestLeftIndex);
  1524. radiusReductionRight = xProtrusionRight / Math.sin(furthestRightAngle + Math.PI/2);
  1525. radiusReductionLeft = xProtrusionLeft / Math.sin(furthestLeftAngle + Math.PI/2);
  1526. // Ensure we actually need to reduce the size of the chart
  1527. radiusReductionRight = (isNumber(radiusReductionRight)) ? radiusReductionRight : 0;
  1528. radiusReductionLeft = (isNumber(radiusReductionLeft)) ? radiusReductionLeft : 0;
  1529. this.drawingArea = largestPossibleRadius - (radiusReductionLeft + radiusReductionRight)/2;
  1530. //this.drawingArea = min([maxWidthRadius, (this.height - (2 * (this.pointLabelFontSize + 5)))/2])
  1531. this.setCenterPoint(radiusReductionLeft, radiusReductionRight);
  1532. },
  1533. setCenterPoint: function(leftMovement, rightMovement){
  1534. var maxRight = this.width - rightMovement - this.drawingArea,
  1535. maxLeft = leftMovement + this.drawingArea;
  1536. this.xCenter = (maxLeft + maxRight)/2;
  1537. // Always vertically in the centre as the text height doesn't change
  1538. this.yCenter = (this.height/2);
  1539. },
  1540. getIndexAngle : function(index){
  1541. var angleMultiplier = (Math.PI * 2) / this.valuesCount;
  1542. // Start from the top instead of right, so remove a quarter of the circle
  1543. return index * angleMultiplier - (Math.PI/2);
  1544. },
  1545. getPointPosition : function(index, distanceFromCenter){
  1546. var thisAngle = this.getIndexAngle(index);
  1547. return {
  1548. x : (Math.cos(thisAngle) * distanceFromCenter) + this.xCenter,
  1549. y : (Math.sin(thisAngle) * distanceFromCenter) + this.yCenter
  1550. };
  1551. },
  1552. draw: function(){
  1553. if (this.display){
  1554. var ctx = this.ctx;
  1555. each(this.yLabels, function(label, index){
  1556. // Don't draw a centre value
  1557. if (index > 0){
  1558. var yCenterOffset = index * (this.drawingArea/this.steps),
  1559. yHeight = this.yCenter - yCenterOffset,
  1560. pointPosition;
  1561. // Draw circular lines around the scale
  1562. if (this.lineWidth > 0){
  1563. ctx.strokeStyle = this.lineColor;
  1564. ctx.lineWidth = this.lineWidth;
  1565. if(this.lineArc){
  1566. ctx.beginPath();
  1567. ctx.arc(this.xCenter, this.yCenter, yCenterOffset, 0, Math.PI*2);
  1568. ctx.closePath();
  1569. ctx.stroke();
  1570. } else{
  1571. ctx.beginPath();
  1572. for (var i=0;i<this.valuesCount;i++)
  1573. {
  1574. pointPosition = this.getPointPosition(i, this.calculateCenterOffset(this.min + (index * this.stepValue)));
  1575. if (i === 0){
  1576. ctx.moveTo(pointPosition.x, pointPosition.y);
  1577. } else {
  1578. ctx.lineTo(pointPosition.x, pointPosition.y);
  1579. }
  1580. }
  1581. ctx.closePath();
  1582. ctx.stroke();
  1583. }
  1584. }
  1585. if(this.showLabels){
  1586. ctx.font = fontString(this.fontSize,this.fontStyle,this.fontFamily);
  1587. if (this.showLabelBackdrop){
  1588. var labelWidth = ctx.measureText(label).width;
  1589. ctx.fillStyle = this.backdropColor;
  1590. ctx.fillRect(
  1591. this.xCenter - labelWidth/2 - this.backdropPaddingX,
  1592. yHeight - this.fontSize/2 - this.backdropPaddingY,
  1593. labelWidth + this.backdropPaddingX*2,
  1594. this.fontSize + this.backdropPaddingY*2
  1595. );
  1596. }
  1597. ctx.textAlign = 'center';
  1598. ctx.textBaseline = "middle";
  1599. ctx.fillStyle = this.fontColor;
  1600. ctx.fillText(label, this.xCenter, yHeight);
  1601. }
  1602. }
  1603. }, this);
  1604. if (!this.lineArc){
  1605. ctx.lineWidth = this.angleLineWidth;
  1606. ctx.strokeStyle = this.angleLineColor;
  1607. for (var i = this.valuesCount - 1; i >= 0; i--) {
  1608. if (this.angleLineWidth > 0){
  1609. var outerPosition = this.getPointPosition(i, this.calculateCenterOffset(this.max));
  1610. ctx.beginPath();
  1611. ctx.moveTo(this.xCenter, this.yCenter);
  1612. ctx.lineTo(outerPosition.x, outerPosition.y);
  1613. ctx.stroke();
  1614. ctx.closePath();
  1615. }
  1616. // Extra 3px out for some label spacing
  1617. var pointLabelPosition = this.getPointPosition(i, this.calculateCenterOffset(this.max) + 5);
  1618. ctx.font = fontString(this.pointLabelFontSize,this.pointLabelFontStyle,this.pointLabelFontFamily);
  1619. ctx.fillStyle = this.pointLabelFontColor;
  1620. var labelsCount = this.labels.length,
  1621. halfLabelsCount = this.labels.length/2,
  1622. quarterLabelsCount = halfLabelsCount/2,
  1623. upperHalf = (i < quarterLabelsCount || i > labelsCount - quarterLabelsCount),
  1624. exactQuarter = (i === quarterLabelsCount || i === labelsCount - quarterLabelsCount);
  1625. if (i === 0){
  1626. ctx.textAlign = 'center';
  1627. } else if(i === halfLabelsCount){
  1628. ctx.textAlign = 'center';
  1629. } else if (i < halfLabelsCount){
  1630. ctx.textAlign = 'left';
  1631. } else {
  1632. ctx.textAlign = 'right';
  1633. }
  1634. // Set the correct text baseline based on outer positioning
  1635. if (exactQuarter){
  1636. ctx.textBaseline = 'middle';
  1637. } else if (upperHalf){
  1638. ctx.textBaseline = 'bottom';
  1639. } else {
  1640. ctx.textBaseline = 'top';
  1641. }
  1642. ctx.fillText(this.labels[i], pointLabelPosition.x, pointLabelPosition.y);
  1643. }
  1644. }
  1645. }
  1646. }
  1647. });
  1648. // Attach global event to resize each chart instance when the browser resizes
  1649. helpers.addEvent(window, "resize", (function(){
  1650. // Basic debounce of resize function so it doesn't hurt performance when resizing browser.
  1651. var timeout;
  1652. return function(){
  1653. clearTimeout(timeout);
  1654. timeout = setTimeout(function(){
  1655. each(Chart.instances,function(instance){
  1656. // If the responsive flag is set in the chart instance config
  1657. // Cascade the resize event down to the chart.
  1658. if (instance.options.responsive){
  1659. instance.resize(instance.render, true);
  1660. }
  1661. });
  1662. }, 50);
  1663. };
  1664. })());
  1665. if (amd) {
  1666. define(function(){
  1667. return Chart;
  1668. });
  1669. } else if (typeof module === 'object' && module.exports) {
  1670. module.exports = Chart;
  1671. }
  1672. root.Chart = Chart;
  1673. Chart.noConflict = function(){
  1674. root.Chart = previous;
  1675. return Chart;
  1676. };
  1677. }).call(this);