Chart.js 115 KB

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