jquery.flot.js 117 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078
  1. /* Javascript plotting library for jQuery, version 0.8.2-alpha.
  2. Copyright (c) 2007-2013 IOLA and Ole Laursen.
  3. Licensed under the MIT license.
  4. */
  5. // first an inline dependency, jquery.colorhelpers.js, we inline it here
  6. // for convenience
  7. /* Plugin for jQuery for working with colors.
  8. *
  9. * Version 1.1.
  10. *
  11. * Inspiration from jQuery color animation plugin by John Resig.
  12. *
  13. * Released under the MIT license by Ole Laursen, October 2009.
  14. *
  15. * Examples:
  16. *
  17. * $.color.parse("#fff").scale('rgb', 0.25).add('a', -0.5).toString()
  18. * var c = $.color.extract($("#mydiv"), 'background-color');
  19. * console.log(c.r, c.g, c.b, c.a);
  20. * $.color.make(100, 50, 25, 0.4).toString() // returns "rgba(100,50,25,0.4)"
  21. *
  22. * Note that .scale() and .add() return the same modified object
  23. * instead of making a new one.
  24. *
  25. * V. 1.1: Fix error handling so e.g. parsing an empty string does
  26. * produce a color rather than just crashing.
  27. */
  28. (function(B){B.color={};B.color.make=function(F,E,C,D){var G={};G.r=F||0;G.g=E||0;G.b=C||0;G.a=D!=null?D:1;G.add=function(J,I){for(var H=0;H<J.length;++H){G[J.charAt(H)]+=I}return G.normalize()};G.scale=function(J,I){for(var H=0;H<J.length;++H){G[J.charAt(H)]*=I}return G.normalize()};G.toString=function(){if(G.a>=1){return"rgb("+[G.r,G.g,G.b].join(",")+")"}else{return"rgba("+[G.r,G.g,G.b,G.a].join(",")+")"}};G.normalize=function(){function H(J,K,I){return K<J?J:(K>I?I:K)}G.r=H(0,parseInt(G.r),255);G.g=H(0,parseInt(G.g),255);G.b=H(0,parseInt(G.b),255);G.a=H(0,G.a,1);return G};G.clone=function(){return B.color.make(G.r,G.b,G.g,G.a)};return G.normalize()};B.color.extract=function(D,C){var E;do{E=D.css(C).toLowerCase();if(E!=""&&E!="transparent"){break}D=D.parent()}while(!B.nodeName(D.get(0),"body"));if(E=="rgba(0, 0, 0, 0)"){E="transparent"}return B.color.parse(E)};B.color.parse=function(F){var E,C=B.color.make;if(E=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(F)){return C(parseInt(E[1],10),parseInt(E[2],10),parseInt(E[3],10))}if(E=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(F)){return C(parseInt(E[1],10),parseInt(E[2],10),parseInt(E[3],10),parseFloat(E[4]))}if(E=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(F)){return C(parseFloat(E[1])*2.55,parseFloat(E[2])*2.55,parseFloat(E[3])*2.55)}if(E=/rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(F)){return C(parseFloat(E[1])*2.55,parseFloat(E[2])*2.55,parseFloat(E[3])*2.55,parseFloat(E[4]))}if(E=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(F)){return C(parseInt(E[1],16),parseInt(E[2],16),parseInt(E[3],16))}if(E=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(F)){return C(parseInt(E[1]+E[1],16),parseInt(E[2]+E[2],16),parseInt(E[3]+E[3],16))}var D=B.trim(F).toLowerCase();if(D=="transparent"){return C(255,255,255,0)}else{E=A[D]||[0,0,0];return C(E[0],E[1],E[2])}};var A={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery);
  29. // the actual Flot code
  30. (function($) {
  31. // Cache the prototype hasOwnProperty for faster access
  32. var hasOwnProperty = Object.prototype.hasOwnProperty;
  33. ///////////////////////////////////////////////////////////////////////////
  34. // The Canvas object is a wrapper around an HTML5 <canvas> tag.
  35. //
  36. // @constructor
  37. // @param {string} cls List of classes to apply to the canvas.
  38. // @param {element} container Element onto which to append the canvas.
  39. //
  40. // Requiring a container is a little iffy, but unfortunately canvas
  41. // operations don't work unless the canvas is attached to the DOM.
  42. function Canvas(cls, container) {
  43. var element = container.children("." + cls)[0];
  44. if (element == null) {
  45. element = document.createElement("canvas");
  46. element.className = cls;
  47. $(element).css({ direction: "ltr", position: "absolute", left: 0, top: 0 })
  48. .appendTo(container);
  49. // If HTML5 Canvas isn't available, fall back to [Ex|Flash]canvas
  50. if (!element.getContext) {
  51. if (window.G_vmlCanvasManager) {
  52. element = window.G_vmlCanvasManager.initElement(element);
  53. } else {
  54. throw new Error("Canvas is not available. If you're using IE with a fall-back such as Excanvas, then there's either a mistake in your conditional include, or the page has no DOCTYPE and is rendering in Quirks Mode.");
  55. }
  56. }
  57. }
  58. this.element = element;
  59. var context = this.context = element.getContext("2d");
  60. // Determine the screen's ratio of physical to device-independent
  61. // pixels. This is the ratio between the canvas width that the browser
  62. // advertises and the number of pixels actually present in that space.
  63. // The iPhone 4, for example, has a device-independent width of 320px,
  64. // but its screen is actually 640px wide. It therefore has a pixel
  65. // ratio of 2, while most normal devices have a ratio of 1.
  66. var devicePixelRatio = window.devicePixelRatio || 1,
  67. backingStoreRatio =
  68. context.webkitBackingStorePixelRatio ||
  69. context.mozBackingStorePixelRatio ||
  70. context.msBackingStorePixelRatio ||
  71. context.oBackingStorePixelRatio ||
  72. context.backingStorePixelRatio || 1;
  73. this.pixelRatio = devicePixelRatio / backingStoreRatio;
  74. // Size the canvas to match the internal dimensions of its container
  75. this.resize(container.width(), container.height());
  76. // Collection of HTML div layers for text overlaid onto the canvas
  77. this.textContainer = null;
  78. this.text = {};
  79. // Cache of text fragments and metrics, so we can avoid expensively
  80. // re-calculating them when the plot is re-rendered in a loop.
  81. this._textCache = {};
  82. }
  83. // Resizes the canvas to the given dimensions.
  84. //
  85. // @param {number} width New width of the canvas, in pixels.
  86. // @param {number} width New height of the canvas, in pixels.
  87. Canvas.prototype.resize = function(width, height) {
  88. if (width <= 0 || height <= 0) {
  89. throw new Error("Invalid dimensions for plot, width = " + width + ", height = " + height);
  90. }
  91. var element = this.element,
  92. context = this.context,
  93. pixelRatio = this.pixelRatio;
  94. // Resize the canvas, increasing its density based on the display's
  95. // pixel ratio; basically giving it more pixels without increasing the
  96. // size of its element, to take advantage of the fact that retina
  97. // displays have that many more pixels in the same advertised space.
  98. // Resizing should reset the state (excanvas seems to be buggy though)
  99. if (this.width != width) {
  100. element.width = width * pixelRatio;
  101. element.style.width = width + "px";
  102. this.width = width;
  103. }
  104. if (this.height != height) {
  105. element.height = height * pixelRatio;
  106. element.style.height = height + "px";
  107. this.height = height;
  108. }
  109. // Save the context, so we can reset in case we get replotted. The
  110. // restore ensure that we're really back at the initial state, and
  111. // should be safe even if we haven't saved the initial state yet.
  112. context.restore();
  113. context.save();
  114. // Scale the coordinate space to match the display density; so even though we
  115. // may have twice as many pixels, we still want lines and other drawing to
  116. // appear at the same size; the extra pixels will just make them crisper.
  117. context.scale(pixelRatio, pixelRatio);
  118. };
  119. // Clears the entire canvas area, not including any overlaid HTML text
  120. Canvas.prototype.clear = function() {
  121. this.context.clearRect(0, 0, this.width, this.height);
  122. };
  123. // Finishes rendering the canvas, including managing the text overlay.
  124. Canvas.prototype.render = function() {
  125. var cache = this._textCache;
  126. // For each text layer, add elements marked as active that haven't
  127. // already been rendered, and remove those that are no longer active.
  128. for (var layerKey in cache) {
  129. if (hasOwnProperty.call(cache, layerKey)) {
  130. var layer = this.getTextLayer(layerKey),
  131. layerCache = cache[layerKey];
  132. layer.hide();
  133. for (var styleKey in layerCache) {
  134. if (hasOwnProperty.call(layerCache, styleKey)) {
  135. var styleCache = layerCache[styleKey];
  136. for (var key in styleCache) {
  137. if (hasOwnProperty.call(styleCache, key)) {
  138. var positions = styleCache[key].positions;
  139. for (var i = 0, position; position = positions[i]; i++) {
  140. if (position.active) {
  141. if (!position.rendered) {
  142. layer.append(position.element);
  143. position.rendered = true;
  144. }
  145. } else {
  146. positions.splice(i--, 1);
  147. if (position.rendered) {
  148. position.element.detach();
  149. }
  150. }
  151. }
  152. if (positions.length == 0) {
  153. delete styleCache[key];
  154. }
  155. }
  156. }
  157. }
  158. }
  159. layer.show();
  160. }
  161. }
  162. };
  163. // Creates (if necessary) and returns the text overlay container.
  164. //
  165. // @param {string} classes String of space-separated CSS classes used to
  166. // uniquely identify the text layer.
  167. // @return {object} The jQuery-wrapped text-layer div.
  168. Canvas.prototype.getTextLayer = function(classes) {
  169. var layer = this.text[classes];
  170. // Create the text layer if it doesn't exist
  171. if (layer == null) {
  172. // Create the text layer container, if it doesn't exist
  173. if (this.textContainer == null) {
  174. this.textContainer = $("<div class='flot-text'></div>")
  175. .css({
  176. position: "absolute",
  177. top: 0,
  178. left: 0,
  179. bottom: 0,
  180. right: 0,
  181. 'font-size': "smaller",
  182. color: "#FFFFFF"
  183. })
  184. .insertAfter(this.element);
  185. }
  186. layer = this.text[classes] = $("<div></div>")
  187. .addClass(classes)
  188. .css({
  189. position: "absolute",
  190. top: 0,
  191. left: 0,
  192. bottom: 0,
  193. right: 0
  194. })
  195. .appendTo(this.textContainer);
  196. }
  197. return layer;
  198. };
  199. // Creates (if necessary) and returns a text info object.
  200. //
  201. // The object looks like this:
  202. //
  203. // {
  204. // width: Width of the text's wrapper div.
  205. // height: Height of the text's wrapper div.
  206. // element: The jQuery-wrapped HTML div containing the text.
  207. // positions: Array of positions at which this text is drawn.
  208. // }
  209. //
  210. // The positions array contains objects that look like this:
  211. //
  212. // {
  213. // active: Flag indicating whether the text should be visible.
  214. // rendered: Flag indicating whether the text is currently visible.
  215. // element: The jQuery-wrapped HTML div containing the text.
  216. // x: X coordinate at which to draw the text.
  217. // y: Y coordinate at which to draw the text.
  218. // }
  219. //
  220. // Each position after the first receives a clone of the original element.
  221. //
  222. // The idea is that that the width, height, and general 'identity' of the
  223. // text is constant no matter where it is placed; the placements are a
  224. // secondary property.
  225. //
  226. // Canvas maintains a cache of recently-used text info objects; getTextInfo
  227. // either returns the cached element or creates a new entry.
  228. //
  229. // @param {string} layer A string of space-separated CSS classes uniquely
  230. // identifying the layer containing this text.
  231. // @param {string} text Text string to retrieve info for.
  232. // @param {(string|object)=} font Either a string of space-separated CSS
  233. // classes or a font-spec object, defining the text's font and style.
  234. // @param {number=} angle Angle at which to rotate the text, in degrees.
  235. // Angle is currently unused, it will be implemented in the future.
  236. // @param {number=} width Maximum width of the text before it wraps.
  237. // @return {object} a text info object.
  238. Canvas.prototype.getTextInfo = function(layer, text, font, angle, width) {
  239. var textStyle, layerCache, styleCache, info;
  240. // Cast the value to a string, in case we were given a number or such
  241. text = "" + text;
  242. // If the font is a font-spec object, generate a CSS font definition
  243. if (typeof font === "object") {
  244. textStyle = font.style + " " + font.variant + " " + font.weight + " " + font.size + "px/" + font.lineHeight + "px " + font.family;
  245. } else {
  246. textStyle = font;
  247. }
  248. // Retrieve (or create) the cache for the text's layer and styles
  249. layerCache = this._textCache[layer];
  250. if (layerCache == null) {
  251. layerCache = this._textCache[layer] = {};
  252. }
  253. styleCache = layerCache[textStyle];
  254. if (styleCache == null) {
  255. styleCache = layerCache[textStyle] = {};
  256. }
  257. info = styleCache[text];
  258. // If we can't find a matching element in our cache, create a new one
  259. if (info == null) {
  260. var element = $("<div></div>").html(text)
  261. .css({
  262. position: "absolute",
  263. 'max-width': width,
  264. top: -9999
  265. })
  266. .appendTo(this.getTextLayer(layer));
  267. if (typeof font === "object") {
  268. element.css({
  269. font: textStyle,
  270. color: font.color
  271. });
  272. } else if (typeof font === "string") {
  273. element.addClass(font);
  274. }
  275. info = styleCache[text] = {
  276. width: element.outerWidth(true),
  277. height: element.outerHeight(true),
  278. element: element,
  279. positions: []
  280. };
  281. element.detach();
  282. }
  283. return info;
  284. };
  285. // Adds a text string to the canvas text overlay.
  286. //
  287. // The text isn't drawn immediately; it is marked as rendering, which will
  288. // result in its addition to the canvas on the next render pass.
  289. //
  290. // @param {string} layer A string of space-separated CSS classes uniquely
  291. // identifying the layer containing this text.
  292. // @param {number} x X coordinate at which to draw the text.
  293. // @param {number} y Y coordinate at which to draw the text.
  294. // @param {string} text Text string to draw.
  295. // @param {(string|object)=} font Either a string of space-separated CSS
  296. // classes or a font-spec object, defining the text's font and style.
  297. // @param {number=} angle Angle at which to rotate the text, in degrees.
  298. // Angle is currently unused, it will be implemented in the future.
  299. // @param {number=} width Maximum width of the text before it wraps.
  300. // @param {string=} halign Horizontal alignment of the text; either "left",
  301. // "center" or "right".
  302. // @param {string=} valign Vertical alignment of the text; either "top",
  303. // "middle" or "bottom".
  304. Canvas.prototype.addText = function(layer, x, y, text, font, angle, width, halign, valign) {
  305. var info = this.getTextInfo(layer, text, font, angle, width),
  306. positions = info.positions;
  307. // Tweak the div's position to match the text's alignment
  308. if (halign == "center") {
  309. x -= info.width / 2;
  310. } else if (halign == "right") {
  311. x -= info.width;
  312. }
  313. if (valign == "middle") {
  314. y -= info.height / 2;
  315. } else if (valign == "bottom") {
  316. y -= info.height;
  317. }
  318. // Determine whether this text already exists at this position.
  319. // If so, mark it for inclusion in the next render pass.
  320. for (var i = 0, position; position = positions[i]; i++) {
  321. if (position.x == x && position.y == y) {
  322. position.active = true;
  323. return;
  324. }
  325. }
  326. // If the text doesn't exist at this position, create a new entry
  327. // For the very first position we'll re-use the original element,
  328. // while for subsequent ones we'll clone it.
  329. position = {
  330. active: true,
  331. rendered: false,
  332. element: positions.length ? info.element.clone() : info.element,
  333. x: x,
  334. y: y
  335. };
  336. positions.push(position);
  337. // Move the element to its final position within the container
  338. position.element.css({
  339. top: Math.round(y),
  340. left: Math.round(x),
  341. 'text-align': halign // In case the text wraps
  342. });
  343. };
  344. // Removes one or more text strings from the canvas text overlay.
  345. //
  346. // If no parameters are given, all text within the layer is removed.
  347. //
  348. // Note that the text is not immediately removed; it is simply marked as
  349. // inactive, which will result in its removal on the next render pass.
  350. // This avoids the performance penalty for 'clear and redraw' behavior,
  351. // where we potentially get rid of all text on a layer, but will likely
  352. // add back most or all of it later, as when redrawing axes, for example.
  353. //
  354. // @param {string} layer A string of space-separated CSS classes uniquely
  355. // identifying the layer containing this text.
  356. // @param {number=} x X coordinate of the text.
  357. // @param {number=} y Y coordinate of the text.
  358. // @param {string=} text Text string to remove.
  359. // @param {(string|object)=} font Either a string of space-separated CSS
  360. // classes or a font-spec object, defining the text's font and style.
  361. // @param {number=} angle Angle at which the text is rotated, in degrees.
  362. // Angle is currently unused, it will be implemented in the future.
  363. Canvas.prototype.removeText = function(layer, x, y, text, font, angle) {
  364. if (text == null) {
  365. var layerCache = this._textCache[layer];
  366. if (layerCache != null) {
  367. for (var styleKey in layerCache) {
  368. if (hasOwnProperty.call(layerCache, styleKey)) {
  369. var styleCache = layerCache[styleKey];
  370. for (var key in styleCache) {
  371. if (hasOwnProperty.call(styleCache, key)) {
  372. var positions = styleCache[key].positions;
  373. for (var i = 0, position; position = positions[i]; i++) {
  374. position.active = false;
  375. }
  376. }
  377. }
  378. }
  379. }
  380. }
  381. } else {
  382. var positions = this.getTextInfo(layer, text, font, angle).positions;
  383. for (var i = 0, position; position = positions[i]; i++) {
  384. if (position.x == x && position.y == y) {
  385. position.active = false;
  386. }
  387. }
  388. }
  389. };
  390. ///////////////////////////////////////////////////////////////////////////
  391. // The top-level container for the entire plot.
  392. function Plot(placeholder, data_, options_, plugins) {
  393. // data is on the form:
  394. // [ series1, series2 ... ]
  395. // where series is either just the data as [ [x1, y1], [x2, y2], ... ]
  396. // or { data: [ [x1, y1], [x2, y2], ... ], label: "some label", ... }
  397. var series = [],
  398. options = {
  399. // the color theme used for graphs
  400. colors: ["#3F97FE","#FF9806","#A62D2D","#25678B","#4F9B2B"],
  401. legend: {
  402. show: true,
  403. color: "rgba(255,255,255,1)",
  404. noColumns: 0, // number of colums in legend table
  405. labelFormatter: null, // fn: string -> string
  406. labelBoxBorderColor: null, // border color for the little label boxes
  407. container: null, // container (as jQuery object) to put legend in, null means default on top of graph
  408. position: "ne", // position of default legend container within plot
  409. margin: [-5, -25], // distance from grid edge to default legend container within plot
  410. backgroundColor: null, // null means auto-detect
  411. backgroundOpacity: 0, // set to 0 to avoid background
  412. sorted: null // default to no legend sorting
  413. },
  414. xaxis: {
  415. show: null, // null = auto-detect, true = always, false = never
  416. position: "bottom", // or "top"
  417. mode: null, // null or "time"
  418. font: null, // null (derived from CSS in placeholder) or object like { size: 11, lineHeight: 13, style: "italic", weight: "bold", family: "sans-serif", variant: "small-caps" }
  419. color: null, // base color, labels, ticks
  420. tickColor: null, // possibly different color of ticks, e.g. "rgba(0,0,0,0.15)"
  421. transform: null, // null or f: number -> number to transform axis
  422. inverseTransform: null, // if transform is set, this should be the inverse function
  423. min: null, // min. value to show, null means set automatically
  424. max: null, // max. value to show, null means set automatically
  425. autoscaleMargin: null, // margin in % to add if auto-setting min/max
  426. ticks: null, // either [1, 3] or [[1, "a"], 3] or (fn: axis info -> ticks) or app. number of ticks for auto-ticks
  427. tickFormatter: null, // fn: number -> string
  428. labelWidth: null, // size of tick labels in pixels
  429. labelHeight: null,
  430. reserveSpace: null, // whether to reserve space even if axis isn't shown
  431. tickLength: null, // size in pixels of ticks, or "full" for whole line
  432. alignTicksWithAxis: null, // axis number or null for no sync
  433. tickDecimals: null, // no. of decimals, null means auto
  434. tickSize: null, // number or [number, "unit"]
  435. minTickSize: null // number or [number, "unit"]
  436. },
  437. yaxis: {
  438. autoscaleMargin: 0.02,
  439. position: "left" // or "right"
  440. },
  441. xaxes: [],
  442. yaxes: [],
  443. series: {
  444. points: {
  445. show: false,
  446. radius: 3,
  447. lineWidth: 2, // in pixels
  448. fill: true,
  449. fillColor: "#ffffff",
  450. symbol: "circle" // or callback
  451. },
  452. lines: {
  453. // we don't put in show: false so we can see
  454. // whether lines were actively disabled
  455. lineWidth: 2, // in pixels
  456. fill: false,
  457. fillColor: null,
  458. steps: false
  459. // Omit 'zero', so we can later default its value to
  460. // match that of the 'fill' option.
  461. },
  462. bars: {
  463. show: false,
  464. lineWidth: 1, // in pixels
  465. barWidth: 1, // in units of the x axis
  466. fill: true,
  467. fillColor: { colors: [ { opacity: 0.7 }, { opacity: 0.8 } ] },
  468. align: "left", // "left", "right", or "center"
  469. horizontal: false,
  470. zero: true
  471. },
  472. shadowSize: 3,
  473. highlightColor: null
  474. },
  475. grid: {
  476. show: true,
  477. aboveData: false,
  478. color: "rgba(255,255,255,0.2)", // primary color used for outline and labels
  479. backgroundColor: null, // null for transparent, else color
  480. borderColor: null, // set if different from the grid color
  481. tickColor: null, // color for the ticks, e.g. "rgba(0,0,0,0.15)"
  482. labelMargin: 5, // in pixels
  483. axisMargin: 8, // in pixels
  484. borderWidth: 1, // in pixels
  485. minBorderMargin: null, // in pixels, null means taken from points radius
  486. markings: null, // array of ranges or fn: axes -> array of ranges
  487. markingsColor: "#000000",
  488. markingsLineWidth: 2,
  489. // interactive stuff
  490. clickable: false,
  491. hoverable: false,
  492. autoHighlight: true, // highlight in case mouse is near
  493. mouseActiveRadius: 5 // how far the mouse can be away to activate an item
  494. },
  495. interaction: {
  496. redrawOverlayInterval: 1000/60 // time between updates, -1 means in same flow
  497. },
  498. hooks: {}
  499. },
  500. surface = null, // the canvas for the plot itself
  501. overlay = null, // canvas for interactive stuff on top of plot
  502. eventHolder = null, // jQuery object that events should be bound to
  503. ctx = null, octx = null,
  504. xaxes = [], yaxes = [],
  505. plotOffset = { left: 0, right: 0, top: 0, bottom: 0},
  506. plotWidth = 0, plotHeight = 0,
  507. hooks = {
  508. processOptions: [],
  509. processRawData: [],
  510. processDatapoints: [],
  511. processOffset: [],
  512. drawBackground: [],
  513. drawSeries: [],
  514. draw: [],
  515. bindEvents: [],
  516. drawOverlay: [],
  517. shutdown: []
  518. },
  519. plot = this;
  520. // public functions
  521. plot.setData = setData;
  522. plot.setupGrid = setupGrid;
  523. plot.draw = draw;
  524. plot.getPlaceholder = function() { return placeholder; };
  525. plot.getCanvas = function() { return surface.element; };
  526. plot.getPlotOffset = function() { return plotOffset; };
  527. plot.width = function () { return plotWidth; };
  528. plot.height = function () { return plotHeight; };
  529. plot.offset = function () {
  530. var o = eventHolder.offset();
  531. o.left += plotOffset.left;
  532. o.top += plotOffset.top;
  533. return o;
  534. };
  535. plot.getData = function () { return series; };
  536. plot.getAxes = function () {
  537. var res = {}, i;
  538. $.each(xaxes.concat(yaxes), function (_, axis) {
  539. if (axis)
  540. res[axis.direction + (axis.n != 1 ? axis.n : "") + "axis"] = axis;
  541. });
  542. return res;
  543. };
  544. plot.getXAxes = function () { return xaxes; };
  545. plot.getYAxes = function () { return yaxes; };
  546. plot.c2p = canvasToAxisCoords;
  547. plot.p2c = axisToCanvasCoords;
  548. plot.getOptions = function () { return options; };
  549. plot.highlight = highlight;
  550. plot.unhighlight = unhighlight;
  551. plot.triggerRedrawOverlay = triggerRedrawOverlay;
  552. plot.pointOffset = function(point) {
  553. return {
  554. left: parseInt(xaxes[axisNumber(point, "x") - 1].p2c(+point.x) + plotOffset.left, 10),
  555. top: parseInt(yaxes[axisNumber(point, "y") - 1].p2c(+point.y) + plotOffset.top, 10)
  556. };
  557. };
  558. plot.shutdown = shutdown;
  559. plot.resize = function () {
  560. var width = placeholder.width(),
  561. height = placeholder.height();
  562. surface.resize(width, height);
  563. overlay.resize(width, height);
  564. };
  565. // public attributes
  566. plot.hooks = hooks;
  567. // initialize
  568. initPlugins(plot);
  569. parseOptions(options_);
  570. setupCanvases();
  571. setData(data_);
  572. setupGrid();
  573. draw();
  574. bindEvents();
  575. function executeHooks(hook, args) {
  576. args = [plot].concat(args);
  577. for (var i = 0; i < hook.length; ++i)
  578. hook[i].apply(this, args);
  579. }
  580. function initPlugins() {
  581. // References to key classes, allowing plugins to modify them
  582. var classes = {
  583. Canvas: Canvas
  584. };
  585. for (var i = 0; i < plugins.length; ++i) {
  586. var p = plugins[i];
  587. p.init(plot, classes);
  588. if (p.options)
  589. $.extend(true, options, p.options);
  590. }
  591. }
  592. function parseOptions(opts) {
  593. $.extend(true, options, opts);
  594. // $.extend merges arrays, rather than replacing them. When less
  595. // colors are provided than the size of the default palette, we
  596. // end up with those colors plus the remaining defaults, which is
  597. // not expected behavior; avoid it by replacing them here.
  598. if (opts && opts.colors) {
  599. options.colors = opts.colors;
  600. }
  601. if (options.xaxis.color == null)
  602. options.xaxis.color = $.color.parse(options.grid.color).scale('a', 0.22).toString();
  603. if (options.yaxis.color == null)
  604. options.yaxis.color = $.color.parse(options.grid.color).scale('a', 0.22).toString();
  605. if (options.xaxis.tickColor == null) // grid.tickColor for back-compatibility
  606. options.xaxis.tickColor = options.grid.tickColor || options.xaxis.color;
  607. if (options.yaxis.tickColor == null) // grid.tickColor for back-compatibility
  608. options.yaxis.tickColor = options.grid.tickColor || options.yaxis.color;
  609. if (options.grid.borderColor == null)
  610. options.grid.borderColor = options.grid.color;
  611. if (options.grid.tickColor == null)
  612. options.grid.tickColor = $.color.parse(options.grid.color).scale('a', 0.22).toString();
  613. // Fill in defaults for axis options, including any unspecified
  614. // font-spec fields, if a font-spec was provided.
  615. // If no x/y axis options were provided, create one of each anyway,
  616. // since the rest of the code assumes that they exist.
  617. var i, axisOptions, axisCount,
  618. fontDefaults = {
  619. style: placeholder.css("font-style"),
  620. size: Math.round(0.8 * (+placeholder.css("font-size").replace("px", "") || 13)),
  621. variant: placeholder.css("font-variant"),
  622. weight: placeholder.css("font-weight"),
  623. family: placeholder.css("font-family")
  624. };
  625. fontDefaults.lineHeight = fontDefaults.size * 1.15;
  626. axisCount = options.xaxes.length || 1;
  627. for (i = 0; i < axisCount; ++i) {
  628. axisOptions = options.xaxes[i];
  629. if (axisOptions && !axisOptions.tickColor) {
  630. axisOptions.tickColor = axisOptions.color;
  631. }
  632. axisOptions = $.extend(true, {}, options.xaxis, axisOptions);
  633. options.xaxes[i] = axisOptions;
  634. if (axisOptions.font) {
  635. axisOptions.font = $.extend({}, fontDefaults, axisOptions.font);
  636. if (!axisOptions.font.color) {
  637. axisOptions.font.color = axisOptions.color;
  638. }
  639. }
  640. }
  641. axisCount = options.yaxes.length || 1;
  642. for (i = 0; i < axisCount; ++i) {
  643. axisOptions = options.yaxes[i];
  644. if (axisOptions && !axisOptions.tickColor) {
  645. axisOptions.tickColor = axisOptions.color;
  646. }
  647. axisOptions = $.extend(true, {}, options.yaxis, axisOptions);
  648. options.yaxes[i] = axisOptions;
  649. if (axisOptions.font) {
  650. axisOptions.font = $.extend({}, fontDefaults, axisOptions.font);
  651. if (!axisOptions.font.color) {
  652. axisOptions.font.color = axisOptions.color;
  653. }
  654. }
  655. }
  656. // backwards compatibility, to be removed in future
  657. if (options.xaxis.noTicks && options.xaxis.ticks == null)
  658. options.xaxis.ticks = options.xaxis.noTicks;
  659. if (options.yaxis.noTicks && options.yaxis.ticks == null)
  660. options.yaxis.ticks = options.yaxis.noTicks;
  661. if (options.x2axis) {
  662. options.xaxes[1] = $.extend(true, {}, options.xaxis, options.x2axis);
  663. options.xaxes[1].position = "top";
  664. }
  665. if (options.y2axis) {
  666. options.yaxes[1] = $.extend(true, {}, options.yaxis, options.y2axis);
  667. options.yaxes[1].position = "right";
  668. }
  669. if (options.grid.coloredAreas)
  670. options.grid.markings = options.grid.coloredAreas;
  671. if (options.grid.coloredAreasColor)
  672. options.grid.markingsColor = options.grid.coloredAreasColor;
  673. if (options.lines)
  674. $.extend(true, options.series.lines, options.lines);
  675. if (options.points)
  676. $.extend(true, options.series.points, options.points);
  677. if (options.bars)
  678. $.extend(true, options.series.bars, options.bars);
  679. if (options.shadowSize != null)
  680. options.series.shadowSize = options.shadowSize;
  681. if (options.highlightColor != null)
  682. options.series.highlightColor = options.highlightColor;
  683. // save options on axes for future reference
  684. for (i = 0; i < options.xaxes.length; ++i)
  685. getOrCreateAxis(xaxes, i + 1).options = options.xaxes[i];
  686. for (i = 0; i < options.yaxes.length; ++i)
  687. getOrCreateAxis(yaxes, i + 1).options = options.yaxes[i];
  688. // add hooks from options
  689. for (var n in hooks)
  690. if (options.hooks[n] && options.hooks[n].length)
  691. hooks[n] = hooks[n].concat(options.hooks[n]);
  692. executeHooks(hooks.processOptions, [options]);
  693. }
  694. function setData(d) {
  695. series = parseData(d);
  696. fillInSeriesOptions();
  697. processData();
  698. }
  699. function parseData(d) {
  700. var res = [];
  701. for (var i = 0; i < d.length; ++i) {
  702. var s = $.extend(true, {}, options.series);
  703. if (d[i].data != null) {
  704. s.data = d[i].data; // move the data instead of deep-copy
  705. delete d[i].data;
  706. $.extend(true, s, d[i]);
  707. d[i].data = s.data;
  708. }
  709. else
  710. s.data = d[i];
  711. res.push(s);
  712. }
  713. return res;
  714. }
  715. function axisNumber(obj, coord) {
  716. var a = obj[coord + "axis"];
  717. if (typeof a == "object") // if we got a real axis, extract number
  718. a = a.n;
  719. if (typeof a != "number")
  720. a = 1; // default to first axis
  721. return a;
  722. }
  723. function allAxes() {
  724. // return flat array without annoying null entries
  725. return $.grep(xaxes.concat(yaxes), function (a) { return a; });
  726. }
  727. function canvasToAxisCoords(pos) {
  728. // return an object with x/y corresponding to all used axes
  729. var res = {}, i, axis;
  730. for (i = 0; i < xaxes.length; ++i) {
  731. axis = xaxes[i];
  732. if (axis && axis.used)
  733. res["x" + axis.n] = axis.c2p(pos.left);
  734. }
  735. for (i = 0; i < yaxes.length; ++i) {
  736. axis = yaxes[i];
  737. if (axis && axis.used)
  738. res["y" + axis.n] = axis.c2p(pos.top);
  739. }
  740. if (res.x1 !== undefined)
  741. res.x = res.x1;
  742. if (res.y1 !== undefined)
  743. res.y = res.y1;
  744. return res;
  745. }
  746. function axisToCanvasCoords(pos) {
  747. // get canvas coords from the first pair of x/y found in pos
  748. var res = {}, i, axis, key;
  749. for (i = 0; i < xaxes.length; ++i) {
  750. axis = xaxes[i];
  751. if (axis && axis.used) {
  752. key = "x" + axis.n;
  753. if (pos[key] == null && axis.n == 1)
  754. key = "x";
  755. if (pos[key] != null) {
  756. res.left = axis.p2c(pos[key]);
  757. break;
  758. }
  759. }
  760. }
  761. for (i = 0; i < yaxes.length; ++i) {
  762. axis = yaxes[i];
  763. if (axis && axis.used) {
  764. key = "y" + axis.n;
  765. if (pos[key] == null && axis.n == 1)
  766. key = "y";
  767. if (pos[key] != null) {
  768. res.top = axis.p2c(pos[key]);
  769. break;
  770. }
  771. }
  772. }
  773. return res;
  774. }
  775. function getOrCreateAxis(axes, number) {
  776. if (!axes[number - 1])
  777. axes[number - 1] = {
  778. n: number, // save the number for future reference
  779. direction: axes == xaxes ? "x" : "y",
  780. options: $.extend(true, {}, axes == xaxes ? options.xaxis : options.yaxis)
  781. };
  782. return axes[number - 1];
  783. }
  784. function fillInSeriesOptions() {
  785. var neededColors = series.length, maxIndex = -1, i;
  786. // Subtract the number of series that already have fixed colors or
  787. // color indexes from the number that we still need to generate.
  788. for (i = 0; i < series.length; ++i) {
  789. var sc = series[i].color;
  790. if (sc != null) {
  791. neededColors--;
  792. if (typeof sc == "number" && sc > maxIndex) {
  793. maxIndex = sc;
  794. }
  795. }
  796. }
  797. // If any of the series have fixed color indexes, then we need to
  798. // generate at least as many colors as the highest index.
  799. if (neededColors <= maxIndex) {
  800. neededColors = maxIndex + 1;
  801. }
  802. // Generate all the colors, using first the option colors and then
  803. // variations on those colors once they're exhausted.
  804. var c, colors = [], colorPool = options.colors,
  805. colorPoolSize = colorPool.length, variation = 0;
  806. for (i = 0; i < neededColors; i++) {
  807. c = $.color.parse(colorPool[i % colorPoolSize] || "#666");
  808. // Each time we exhaust the colors in the pool we adjust
  809. // a scaling factor used to produce more variations on
  810. // those colors. The factor alternates negative/positive
  811. // to produce lighter/darker colors.
  812. // Reset the variation after every few cycles, or else
  813. // it will end up producing only white or black colors.
  814. if (i % colorPoolSize == 0 && i) {
  815. if (variation >= 0) {
  816. if (variation < 0.5) {
  817. variation = -variation - 0.2;
  818. } else variation = 0;
  819. } else variation = -variation;
  820. }
  821. colors[i] = c.scale('rgb', 1 + variation);
  822. }
  823. // Finalize the series options, filling in their colors
  824. var colori = 0, s;
  825. for (i = 0; i < series.length; ++i) {
  826. s = series[i];
  827. // assign colors
  828. if (s.color == null) {
  829. s.color = colors[colori].toString();
  830. ++colori;
  831. }
  832. else if (typeof s.color == "number")
  833. s.color = colors[s.color].toString();
  834. // turn on lines automatically in case nothing is set
  835. if (s.lines.show == null) {
  836. var v, show = true;
  837. for (v in s)
  838. if (s[v] && s[v].show) {
  839. show = false;
  840. break;
  841. }
  842. if (show)
  843. s.lines.show = true;
  844. }
  845. // If nothing was provided for lines.zero, default it to match
  846. // lines.fill, since areas by default should extend to zero.
  847. if (s.lines.zero == null) {
  848. s.lines.zero = !!s.lines.fill;
  849. }
  850. // setup axes
  851. s.xaxis = getOrCreateAxis(xaxes, axisNumber(s, "x"));
  852. s.yaxis = getOrCreateAxis(yaxes, axisNumber(s, "y"));
  853. }
  854. }
  855. function processData() {
  856. var topSentry = Number.POSITIVE_INFINITY,
  857. bottomSentry = Number.NEGATIVE_INFINITY,
  858. fakeInfinity = Number.MAX_VALUE,
  859. i, j, k, m, length,
  860. s, points, ps, x, y, axis, val, f, p,
  861. data, format;
  862. function updateAxis(axis, min, max) {
  863. if (min < axis.datamin && min != -fakeInfinity)
  864. axis.datamin = min;
  865. if (max > axis.datamax && max != fakeInfinity)
  866. axis.datamax = max;
  867. }
  868. $.each(allAxes(), function (_, axis) {
  869. // init axis
  870. axis.datamin = topSentry;
  871. axis.datamax = bottomSentry;
  872. axis.used = false;
  873. });
  874. for (i = 0; i < series.length; ++i) {
  875. s = series[i];
  876. s.datapoints = { points: [] };
  877. executeHooks(hooks.processRawData, [ s, s.data, s.datapoints ]);
  878. }
  879. // first pass: clean and copy data
  880. for (i = 0; i < series.length; ++i) {
  881. s = series[i];
  882. data = s.data;
  883. format = s.datapoints.format;
  884. if (!format) {
  885. format = [];
  886. // find out how to copy
  887. format.push({ x: true, number: true, required: true });
  888. format.push({ y: true, number: true, required: true });
  889. if (s.bars.show || (s.lines.show && s.lines.fill)) {
  890. var autoscale = !!((s.bars.show && s.bars.zero) || (s.lines.show && s.lines.zero));
  891. format.push({ y: true, number: true, required: false, defaultValue: 0, autoscale: autoscale });
  892. if (s.bars.horizontal) {
  893. delete format[format.length - 1].y;
  894. format[format.length - 1].x = true;
  895. }
  896. }
  897. s.datapoints.format = format;
  898. }
  899. if (s.datapoints.pointsize != null)
  900. continue; // already filled in
  901. s.datapoints.pointsize = format.length;
  902. ps = s.datapoints.pointsize;
  903. points = s.datapoints.points;
  904. var insertSteps = s.lines.show && s.lines.steps;
  905. s.xaxis.used = s.yaxis.used = true;
  906. for (j = k = 0; j < data.length; ++j, k += ps) {
  907. p = data[j];
  908. var nullify = p == null;
  909. if (!nullify) {
  910. for (m = 0; m < ps; ++m) {
  911. val = p[m];
  912. f = format[m];
  913. if (f) {
  914. if (f.number && val != null) {
  915. val = +val; // convert to number
  916. if (isNaN(val))
  917. val = null;
  918. else if (val == Infinity)
  919. val = fakeInfinity;
  920. else if (val == -Infinity)
  921. val = -fakeInfinity;
  922. }
  923. if (val == null) {
  924. if (f.required)
  925. nullify = true;
  926. if (f.defaultValue != null)
  927. val = f.defaultValue;
  928. }
  929. }
  930. points[k + m] = val;
  931. }
  932. }
  933. if (nullify) {
  934. for (m = 0; m < ps; ++m) {
  935. val = points[k + m];
  936. if (val != null) {
  937. f = format[m];
  938. // extract min/max info
  939. if (f.autoscale !== false) {
  940. if (f.x) {
  941. updateAxis(s.xaxis, val, val);
  942. }
  943. if (f.y) {
  944. updateAxis(s.yaxis, val, val);
  945. }
  946. }
  947. }
  948. points[k + m] = null;
  949. }
  950. }
  951. else {
  952. // a little bit of line specific stuff that
  953. // perhaps shouldn't be here, but lacking
  954. // better means...
  955. if (insertSteps && k > 0
  956. && points[k - ps] != null
  957. && points[k - ps] != points[k]
  958. && points[k - ps + 1] != points[k + 1]) {
  959. // copy the point to make room for a middle point
  960. for (m = 0; m < ps; ++m)
  961. points[k + ps + m] = points[k + m];
  962. // middle point has same y
  963. points[k + 1] = points[k - ps + 1];
  964. // we've added a point, better reflect that
  965. k += ps;
  966. }
  967. }
  968. }
  969. }
  970. // give the hooks a chance to run
  971. for (i = 0; i < series.length; ++i) {
  972. s = series[i];
  973. executeHooks(hooks.processDatapoints, [ s, s.datapoints]);
  974. }
  975. // second pass: find datamax/datamin for auto-scaling
  976. for (i = 0; i < series.length; ++i) {
  977. s = series[i];
  978. points = s.datapoints.points;
  979. ps = s.datapoints.pointsize;
  980. format = s.datapoints.format;
  981. var xmin = topSentry, ymin = topSentry,
  982. xmax = bottomSentry, ymax = bottomSentry;
  983. for (j = 0; j < points.length; j += ps) {
  984. if (points[j] == null)
  985. continue;
  986. for (m = 0; m < ps; ++m) {
  987. val = points[j + m];
  988. f = format[m];
  989. if (!f || f.autoscale === false || val == fakeInfinity || val == -fakeInfinity)
  990. continue;
  991. if (f.x) {
  992. if (val < xmin)
  993. xmin = val;
  994. if (val > xmax)
  995. xmax = val;
  996. }
  997. if (f.y) {
  998. if (val < ymin)
  999. ymin = val;
  1000. if (val > ymax)
  1001. ymax = val;
  1002. }
  1003. }
  1004. }
  1005. if (s.bars.show) {
  1006. // make sure we got room for the bar on the dancing floor
  1007. var delta;
  1008. switch (s.bars.align) {
  1009. case "left":
  1010. delta = 0;
  1011. break;
  1012. case "right":
  1013. delta = -s.bars.barWidth;
  1014. break;
  1015. default:
  1016. delta = -s.bars.barWidth / 2;
  1017. }
  1018. if (s.bars.horizontal) {
  1019. ymin += delta;
  1020. ymax += delta + s.bars.barWidth;
  1021. }
  1022. else {
  1023. xmin += delta;
  1024. xmax += delta + s.bars.barWidth;
  1025. }
  1026. }
  1027. updateAxis(s.xaxis, xmin, xmax);
  1028. updateAxis(s.yaxis, ymin, ymax);
  1029. }
  1030. $.each(allAxes(), function (_, axis) {
  1031. if (axis.datamin == topSentry)
  1032. axis.datamin = null;
  1033. if (axis.datamax == bottomSentry)
  1034. axis.datamax = null;
  1035. });
  1036. }
  1037. function setupCanvases() {
  1038. // Make sure the placeholder is clear of everything except canvases
  1039. // from a previous plot in this container that we'll try to re-use.
  1040. placeholder.css("padding", 0) // padding messes up the positioning
  1041. .children(":not(.flot-base,.flot-overlay)").remove();
  1042. if (placeholder.css("position") == 'static')
  1043. placeholder.css("position", "relative"); // for positioning labels and overlay
  1044. surface = new Canvas("flot-base", placeholder);
  1045. overlay = new Canvas("flot-overlay", placeholder); // overlay canvas for interactive features
  1046. ctx = surface.context;
  1047. octx = overlay.context;
  1048. // define which element we're listening for events on
  1049. eventHolder = $(overlay.element).unbind();
  1050. // If we're re-using a plot object, shut down the old one
  1051. var existing = placeholder.data("plot");
  1052. if (existing) {
  1053. existing.shutdown();
  1054. overlay.clear();
  1055. }
  1056. // save in case we get replotted
  1057. placeholder.data("plot", plot);
  1058. }
  1059. function bindEvents() {
  1060. // bind events
  1061. if (options.grid.hoverable) {
  1062. eventHolder.mousemove(onMouseMove);
  1063. // Use bind, rather than .mouseleave, because we officially
  1064. // still support jQuery 1.2.6, which doesn't define a shortcut
  1065. // for mouseenter or mouseleave. This was a bug/oversight that
  1066. // was fixed somewhere around 1.3.x. We can return to using
  1067. // .mouseleave when we drop support for 1.2.6.
  1068. eventHolder.bind("mouseleave", onMouseLeave);
  1069. }
  1070. if (options.grid.clickable)
  1071. eventHolder.click(onClick);
  1072. executeHooks(hooks.bindEvents, [eventHolder]);
  1073. }
  1074. function shutdown() {
  1075. if (redrawTimeout)
  1076. clearTimeout(redrawTimeout);
  1077. eventHolder.unbind("mousemove", onMouseMove);
  1078. eventHolder.unbind("mouseleave", onMouseLeave);
  1079. eventHolder.unbind("click", onClick);
  1080. executeHooks(hooks.shutdown, [eventHolder]);
  1081. }
  1082. function setTransformationHelpers(axis) {
  1083. // set helper functions on the axis, assumes plot area
  1084. // has been computed already
  1085. function identity(x) { return x; }
  1086. var s, m, t = axis.options.transform || identity,
  1087. it = axis.options.inverseTransform;
  1088. // precompute how much the axis is scaling a point
  1089. // in canvas space
  1090. if (axis.direction == "x") {
  1091. s = axis.scale = plotWidth / Math.abs(t(axis.max) - t(axis.min));
  1092. m = Math.min(t(axis.max), t(axis.min));
  1093. }
  1094. else {
  1095. s = axis.scale = plotHeight / Math.abs(t(axis.max) - t(axis.min));
  1096. s = -s;
  1097. m = Math.max(t(axis.max), t(axis.min));
  1098. }
  1099. // data point to canvas coordinate
  1100. if (t == identity) // slight optimization
  1101. axis.p2c = function (p) { return (p - m) * s; };
  1102. else
  1103. axis.p2c = function (p) { return (t(p) - m) * s; };
  1104. // canvas coordinate to data point
  1105. if (!it)
  1106. axis.c2p = function (c) { return m + c / s; };
  1107. else
  1108. axis.c2p = function (c) { return it(m + c / s); };
  1109. }
  1110. function measureTickLabels(axis) {
  1111. var opts = axis.options,
  1112. ticks = axis.ticks || [],
  1113. labelWidth = opts.labelWidth || 0,
  1114. labelHeight = opts.labelHeight || 0,
  1115. maxWidth = labelWidth || axis.direction == "x" ? Math.floor(surface.width / (ticks.length || 1)) : null,
  1116. legacyStyles = axis.direction + "Axis " + axis.direction + axis.n + "Axis",
  1117. layer = "flot-" + axis.direction + "-axis flot-" + axis.direction + axis.n + "-axis " + legacyStyles,
  1118. font = opts.font || "flot-tick-label tickLabel";
  1119. for (var i = 0; i < ticks.length; ++i) {
  1120. var t = ticks[i];
  1121. if (!t.label)
  1122. continue;
  1123. var info = surface.getTextInfo(layer, t.label, font, null, maxWidth);
  1124. labelWidth = Math.max(labelWidth, info.width);
  1125. labelHeight = Math.max(labelHeight, info.height);
  1126. }
  1127. axis.labelWidth = opts.labelWidth || labelWidth;
  1128. axis.labelHeight = opts.labelHeight || labelHeight;
  1129. }
  1130. function allocateAxisBoxFirstPhase(axis) {
  1131. // find the bounding box of the axis by looking at label
  1132. // widths/heights and ticks, make room by diminishing the
  1133. // plotOffset; this first phase only looks at one
  1134. // dimension per axis, the other dimension depends on the
  1135. // other axes so will have to wait
  1136. var lw = axis.labelWidth,
  1137. lh = axis.labelHeight,
  1138. pos = axis.options.position,
  1139. tickLength = axis.options.tickLength,
  1140. axisMargin = options.grid.axisMargin,
  1141. padding = options.grid.labelMargin,
  1142. all = axis.direction == "x" ? xaxes : yaxes,
  1143. index, innermost;
  1144. // determine axis margin
  1145. var samePosition = $.grep(all, function (a) {
  1146. return a && a.options.position == pos && a.reserveSpace;
  1147. });
  1148. if ($.inArray(axis, samePosition) == samePosition.length - 1)
  1149. axisMargin = 0; // outermost
  1150. // Determine whether the axis is the first (innermost) on its side
  1151. innermost = $.inArray(axis, samePosition) == 0;
  1152. // determine tick length - if we're innermost, we can use "full"
  1153. if (tickLength == null) {
  1154. if (innermost)
  1155. tickLength = "full";
  1156. else
  1157. tickLength = 5;
  1158. }
  1159. if (!isNaN(+tickLength))
  1160. padding += +tickLength;
  1161. // compute box
  1162. if (axis.direction == "x") {
  1163. lh += padding;
  1164. if (pos == "bottom") {
  1165. plotOffset.bottom += lh + axisMargin;
  1166. axis.box = { top: surface.height - plotOffset.bottom, height: lh };
  1167. }
  1168. else {
  1169. axis.box = { top: plotOffset.top + axisMargin, height: lh };
  1170. plotOffset.top += lh + axisMargin;
  1171. }
  1172. }
  1173. else {
  1174. lw += padding;
  1175. if (pos == "left") {
  1176. axis.box = { left: plotOffset.left + axisMargin, width: lw };
  1177. plotOffset.left += lw + axisMargin;
  1178. }
  1179. else {
  1180. plotOffset.right += lw + axisMargin;
  1181. axis.box = { left: surface.width - plotOffset.right, width: lw };
  1182. }
  1183. }
  1184. // save for future reference
  1185. axis.position = pos;
  1186. axis.tickLength = tickLength;
  1187. axis.box.padding = padding;
  1188. axis.innermost = innermost;
  1189. }
  1190. function allocateAxisBoxSecondPhase(axis) {
  1191. // now that all axis boxes have been placed in one
  1192. // dimension, we can set the remaining dimension coordinates
  1193. if (axis.direction == "x") {
  1194. axis.box.left = plotOffset.left - axis.labelWidth / 2;
  1195. axis.box.width = surface.width - plotOffset.left - plotOffset.right + axis.labelWidth;
  1196. }
  1197. else {
  1198. axis.box.top = plotOffset.top - axis.labelHeight / 2;
  1199. axis.box.height = surface.height - plotOffset.bottom - plotOffset.top + axis.labelHeight;
  1200. }
  1201. }
  1202. function adjustLayoutForThingsStickingOut() {
  1203. // possibly adjust plot offset to ensure everything stays
  1204. // inside the canvas and isn't clipped off
  1205. var minMargin = options.grid.minBorderMargin,
  1206. margins = { x: 0, y: 0 }, i, axis;
  1207. // check stuff from the plot (FIXME: this should just read
  1208. // a value from the series, otherwise it's impossible to
  1209. // customize)
  1210. if (minMargin == null) {
  1211. minMargin = 0;
  1212. for (i = 0; i < series.length; ++i)
  1213. minMargin = Math.max(minMargin, 2 * (series[i].points.radius + series[i].points.lineWidth/2));
  1214. }
  1215. margins.x = margins.y = Math.ceil(minMargin);
  1216. // check axis labels, note we don't check the actual
  1217. // labels but instead use the overall width/height to not
  1218. // jump as much around with replots
  1219. $.each(allAxes(), function (_, axis) {
  1220. var dir = axis.direction;
  1221. if (axis.reserveSpace)
  1222. margins[dir] = Math.ceil(Math.max(margins[dir], (dir == "x" ? axis.labelWidth : axis.labelHeight) / 2));
  1223. });
  1224. plotOffset.left = Math.max(margins.x, plotOffset.left);
  1225. plotOffset.right = Math.max(margins.x, plotOffset.right);
  1226. plotOffset.top = Math.max(margins.y, plotOffset.top);
  1227. plotOffset.bottom = Math.max(margins.y, plotOffset.bottom);
  1228. }
  1229. function setupGrid() {
  1230. var i, axes = allAxes(), showGrid = options.grid.show;
  1231. // Initialize the plot's offset from the edge of the canvas
  1232. for (var a in plotOffset) {
  1233. var margin = options.grid.margin || 0;
  1234. plotOffset[a] = typeof margin == "number" ? margin : margin[a] || 0;
  1235. }
  1236. executeHooks(hooks.processOffset, [plotOffset]);
  1237. // If the grid is visible, add its border width to the offset
  1238. for (var a in plotOffset) {
  1239. if(typeof(options.grid.borderWidth) == "object") {
  1240. plotOffset[a] += showGrid ? options.grid.borderWidth[a] : 0;
  1241. }
  1242. else {
  1243. plotOffset[a] += showGrid ? options.grid.borderWidth : 0;
  1244. }
  1245. }
  1246. // init axes
  1247. $.each(axes, function (_, axis) {
  1248. axis.show = axis.options.show;
  1249. if (axis.show == null)
  1250. axis.show = axis.used; // by default an axis is visible if it's got data
  1251. axis.reserveSpace = axis.show || axis.options.reserveSpace;
  1252. setRange(axis);
  1253. });
  1254. if (showGrid) {
  1255. var allocatedAxes = $.grep(axes, function (axis) { return axis.reserveSpace; });
  1256. $.each(allocatedAxes, function (_, axis) {
  1257. // make the ticks
  1258. setupTickGeneration(axis);
  1259. setTicks(axis);
  1260. snapRangeToTicks(axis, axis.ticks);
  1261. // find labelWidth/Height for axis
  1262. measureTickLabels(axis);
  1263. });
  1264. // with all dimensions calculated, we can compute the
  1265. // axis bounding boxes, start from the outside
  1266. // (reverse order)
  1267. for (i = allocatedAxes.length - 1; i >= 0; --i)
  1268. allocateAxisBoxFirstPhase(allocatedAxes[i]);
  1269. // make sure we've got enough space for things that
  1270. // might stick out
  1271. adjustLayoutForThingsStickingOut();
  1272. $.each(allocatedAxes, function (_, axis) {
  1273. allocateAxisBoxSecondPhase(axis);
  1274. });
  1275. }
  1276. plotWidth = surface.width - plotOffset.left - plotOffset.right;
  1277. plotHeight = surface.height - plotOffset.bottom - plotOffset.top;
  1278. // now we got the proper plot dimensions, we can compute the scaling
  1279. $.each(axes, function (_, axis) {
  1280. setTransformationHelpers(axis);
  1281. });
  1282. if (showGrid) {
  1283. drawAxisLabels();
  1284. }
  1285. insertLegend();
  1286. }
  1287. function setRange(axis) {
  1288. var opts = axis.options,
  1289. min = +(opts.min != null ? opts.min : axis.datamin),
  1290. max = +(opts.max != null ? opts.max : axis.datamax),
  1291. delta = max - min;
  1292. if (delta == 0.0) {
  1293. // degenerate case
  1294. var widen = max == 0 ? 1 : 0.01;
  1295. if (opts.min == null)
  1296. min -= widen;
  1297. // always widen max if we couldn't widen min to ensure we
  1298. // don't fall into min == max which doesn't work
  1299. if (opts.max == null || opts.min != null)
  1300. max += widen;
  1301. }
  1302. else {
  1303. // consider autoscaling
  1304. var margin = opts.autoscaleMargin;
  1305. if (margin != null) {
  1306. if (opts.min == null) {
  1307. min -= delta * margin;
  1308. // make sure we don't go below zero if all values
  1309. // are positive
  1310. if (min < 0 && axis.datamin != null && axis.datamin >= 0)
  1311. min = 0;
  1312. }
  1313. if (opts.max == null) {
  1314. max += delta * margin;
  1315. if (max > 0 && axis.datamax != null && axis.datamax <= 0)
  1316. max = 0;
  1317. }
  1318. }
  1319. }
  1320. axis.min = min;
  1321. axis.max = max;
  1322. }
  1323. function setupTickGeneration(axis) {
  1324. var opts = axis.options;
  1325. // estimate number of ticks
  1326. var noTicks;
  1327. if (typeof opts.ticks == "number" && opts.ticks > 0)
  1328. noTicks = opts.ticks;
  1329. else
  1330. // heuristic based on the model a*sqrt(x) fitted to
  1331. // some data points that seemed reasonable
  1332. noTicks = 0.3 * Math.sqrt(axis.direction == "x" ? surface.width : surface.height);
  1333. var delta = (axis.max - axis.min) / noTicks,
  1334. dec = -Math.floor(Math.log(delta) / Math.LN10),
  1335. maxDec = opts.tickDecimals;
  1336. if (maxDec != null && dec > maxDec) {
  1337. dec = maxDec;
  1338. }
  1339. var magn = Math.pow(10, -dec),
  1340. norm = delta / magn, // norm is between 1.0 and 10.0
  1341. size;
  1342. if (norm < 1.5) {
  1343. size = 1;
  1344. } else if (norm < 3) {
  1345. size = 2;
  1346. // special case for 2.5, requires an extra decimal
  1347. if (norm > 2.25 && (maxDec == null || dec + 1 <= maxDec)) {
  1348. size = 2.5;
  1349. ++dec;
  1350. }
  1351. } else if (norm < 7.5) {
  1352. size = 5;
  1353. } else {
  1354. size = 10;
  1355. }
  1356. size *= magn;
  1357. if (opts.minTickSize != null && size < opts.minTickSize) {
  1358. size = opts.minTickSize;
  1359. }
  1360. axis.delta = delta;
  1361. axis.tickDecimals = Math.max(0, maxDec != null ? maxDec : dec);
  1362. axis.tickSize = opts.tickSize || size;
  1363. // Time mode was moved to a plug-in in 0.8, but since so many people use this
  1364. // we'll add an especially friendly make sure they remembered to include it.
  1365. if (opts.mode == "time" && !axis.tickGenerator) {
  1366. throw new Error("Time mode requires the flot.time plugin.");
  1367. }
  1368. // Flot supports base-10 axes; any other mode else is handled by a plug-in,
  1369. // like flot.time.js.
  1370. if (!axis.tickGenerator) {
  1371. axis.tickGenerator = function (axis) {
  1372. var ticks = [],
  1373. start = floorInBase(axis.min, axis.tickSize),
  1374. i = 0,
  1375. v = Number.NaN,
  1376. prev;
  1377. do {
  1378. prev = v;
  1379. v = start + i * axis.tickSize;
  1380. ticks.push(v);
  1381. ++i;
  1382. } while (v < axis.max && v != prev);
  1383. return ticks;
  1384. };
  1385. axis.tickFormatter = function (value, axis) {
  1386. var factor = axis.tickDecimals ? Math.pow(10, axis.tickDecimals) : 1;
  1387. var formatted = "" + Math.round(value * factor) / factor;
  1388. // If tickDecimals was specified, ensure that we have exactly that
  1389. // much precision; otherwise default to the value's own precision.
  1390. if (axis.tickDecimals != null) {
  1391. var decimal = formatted.indexOf(".");
  1392. var precision = decimal == -1 ? 0 : formatted.length - decimal - 1;
  1393. if (precision < axis.tickDecimals) {
  1394. return (precision ? formatted : formatted + ".") + ("" + factor).substr(1, axis.tickDecimals - precision);
  1395. }
  1396. }
  1397. return formatted;
  1398. };
  1399. }
  1400. if ($.isFunction(opts.tickFormatter))
  1401. axis.tickFormatter = function (v, axis) { return "" + opts.tickFormatter(v, axis); };
  1402. if (opts.alignTicksWithAxis != null) {
  1403. var otherAxis = (axis.direction == "x" ? xaxes : yaxes)[opts.alignTicksWithAxis - 1];
  1404. if (otherAxis && otherAxis.used && otherAxis != axis) {
  1405. // consider snapping min/max to outermost nice ticks
  1406. var niceTicks = axis.tickGenerator(axis);
  1407. if (niceTicks.length > 0) {
  1408. if (opts.min == null)
  1409. axis.min = Math.min(axis.min, niceTicks[0]);
  1410. if (opts.max == null && niceTicks.length > 1)
  1411. axis.max = Math.max(axis.max, niceTicks[niceTicks.length - 1]);
  1412. }
  1413. axis.tickGenerator = function (axis) {
  1414. // copy ticks, scaled to this axis
  1415. var ticks = [], v, i;
  1416. for (i = 0; i < otherAxis.ticks.length; ++i) {
  1417. v = (otherAxis.ticks[i].v - otherAxis.min) / (otherAxis.max - otherAxis.min);
  1418. v = axis.min + v * (axis.max - axis.min);
  1419. ticks.push(v);
  1420. }
  1421. return ticks;
  1422. };
  1423. // we might need an extra decimal since forced
  1424. // ticks don't necessarily fit naturally
  1425. if (!axis.mode && opts.tickDecimals == null) {
  1426. var extraDec = Math.max(0, -Math.floor(Math.log(axis.delta) / Math.LN10) + 1),
  1427. ts = axis.tickGenerator(axis);
  1428. // only proceed if the tick interval rounded
  1429. // with an extra decimal doesn't give us a
  1430. // zero at end
  1431. if (!(ts.length > 1 && /\..*0$/.test((ts[1] - ts[0]).toFixed(extraDec))))
  1432. axis.tickDecimals = extraDec;
  1433. }
  1434. }
  1435. }
  1436. }
  1437. function setTicks(axis) {
  1438. var oticks = axis.options.ticks, ticks = [];
  1439. if (oticks == null || (typeof oticks == "number" && oticks > 0))
  1440. ticks = axis.tickGenerator(axis);
  1441. else if (oticks) {
  1442. if ($.isFunction(oticks))
  1443. // generate the ticks
  1444. ticks = oticks(axis);
  1445. else
  1446. ticks = oticks;
  1447. }
  1448. // clean up/labelify the supplied ticks, copy them over
  1449. var i, v;
  1450. axis.ticks = [];
  1451. for (i = 0; i < ticks.length; ++i) {
  1452. var label = null;
  1453. var t = ticks[i];
  1454. if (typeof t == "object") {
  1455. v = +t[0];
  1456. if (t.length > 1)
  1457. label = t[1];
  1458. }
  1459. else
  1460. v = +t;
  1461. if (label == null)
  1462. label = axis.tickFormatter(v, axis);
  1463. if (!isNaN(v))
  1464. axis.ticks.push({ v: v, label: label });
  1465. }
  1466. }
  1467. function snapRangeToTicks(axis, ticks) {
  1468. if (axis.options.autoscaleMargin && ticks.length > 0) {
  1469. // snap to ticks
  1470. if (axis.options.min == null)
  1471. axis.min = Math.min(axis.min, ticks[0].v);
  1472. if (axis.options.max == null && ticks.length > 1)
  1473. axis.max = Math.max(axis.max, ticks[ticks.length - 1].v);
  1474. }
  1475. }
  1476. function draw() {
  1477. surface.clear();
  1478. executeHooks(hooks.drawBackground, [ctx]);
  1479. var grid = options.grid;
  1480. // draw background, if any
  1481. if (grid.show && grid.backgroundColor)
  1482. drawBackground();
  1483. if (grid.show && !grid.aboveData) {
  1484. drawGrid();
  1485. }
  1486. for (var i = 0; i < series.length; ++i) {
  1487. executeHooks(hooks.drawSeries, [ctx, series[i]]);
  1488. drawSeries(series[i]);
  1489. }
  1490. executeHooks(hooks.draw, [ctx]);
  1491. if (grid.show && grid.aboveData) {
  1492. drawGrid();
  1493. }
  1494. surface.render();
  1495. // A draw implies that either the axes or data have changed, so we
  1496. // should probably update the overlay highlights as well.
  1497. triggerRedrawOverlay();
  1498. }
  1499. function extractRange(ranges, coord) {
  1500. var axis, from, to, key, axes = allAxes();
  1501. for (var i = 0; i < axes.length; ++i) {
  1502. axis = axes[i];
  1503. if (axis.direction == coord) {
  1504. key = coord + axis.n + "axis";
  1505. if (!ranges[key] && axis.n == 1)
  1506. key = coord + "axis"; // support x1axis as xaxis
  1507. if (ranges[key]) {
  1508. from = ranges[key].from;
  1509. to = ranges[key].to;
  1510. break;
  1511. }
  1512. }
  1513. }
  1514. // backwards-compat stuff - to be removed in future
  1515. if (!ranges[key]) {
  1516. axis = coord == "x" ? xaxes[0] : yaxes[0];
  1517. from = ranges[coord + "1"];
  1518. to = ranges[coord + "2"];
  1519. }
  1520. // auto-reverse as an added bonus
  1521. if (from != null && to != null && from > to) {
  1522. var tmp = from;
  1523. from = to;
  1524. to = tmp;
  1525. }
  1526. return { from: from, to: to, axis: axis };
  1527. }
  1528. function drawBackground() {
  1529. ctx.save();
  1530. ctx.translate(plotOffset.left, plotOffset.top);
  1531. ctx.fillStyle = getColorOrGradient(options.grid.backgroundColor, plotHeight, 0, "rgba(255, 255, 255, 0)");
  1532. ctx.fillRect(0, 0, plotWidth, plotHeight);
  1533. ctx.restore();
  1534. }
  1535. function drawGrid() {
  1536. var i, axes, bw, bc;
  1537. ctx.save();
  1538. ctx.translate(plotOffset.left, plotOffset.top);
  1539. // draw markings
  1540. var markings = options.grid.markings;
  1541. if (markings) {
  1542. if ($.isFunction(markings)) {
  1543. axes = plot.getAxes();
  1544. // xmin etc. is backwards compatibility, to be
  1545. // removed in the future
  1546. axes.xmin = axes.xaxis.min;
  1547. axes.xmax = axes.xaxis.max;
  1548. axes.ymin = axes.yaxis.min;
  1549. axes.ymax = axes.yaxis.max;
  1550. markings = markings(axes);
  1551. }
  1552. for (i = 0; i < markings.length; ++i) {
  1553. var m = markings[i],
  1554. xrange = extractRange(m, "x"),
  1555. yrange = extractRange(m, "y");
  1556. // fill in missing
  1557. if (xrange.from == null)
  1558. xrange.from = xrange.axis.min;
  1559. if (xrange.to == null)
  1560. xrange.to = xrange.axis.max;
  1561. if (yrange.from == null)
  1562. yrange.from = yrange.axis.min;
  1563. if (yrange.to == null)
  1564. yrange.to = yrange.axis.max;
  1565. // clip
  1566. if (xrange.to < xrange.axis.min || xrange.from > xrange.axis.max ||
  1567. yrange.to < yrange.axis.min || yrange.from > yrange.axis.max)
  1568. continue;
  1569. xrange.from = Math.max(xrange.from, xrange.axis.min);
  1570. xrange.to = Math.min(xrange.to, xrange.axis.max);
  1571. yrange.from = Math.max(yrange.from, yrange.axis.min);
  1572. yrange.to = Math.min(yrange.to, yrange.axis.max);
  1573. if (xrange.from == xrange.to && yrange.from == yrange.to)
  1574. continue;
  1575. // then draw
  1576. xrange.from = xrange.axis.p2c(xrange.from);
  1577. xrange.to = xrange.axis.p2c(xrange.to);
  1578. yrange.from = yrange.axis.p2c(yrange.from);
  1579. yrange.to = yrange.axis.p2c(yrange.to);
  1580. if (xrange.from == xrange.to || yrange.from == yrange.to) {
  1581. // draw line
  1582. ctx.beginPath();
  1583. ctx.strokeStyle = m.color || options.grid.markingsColor;
  1584. ctx.lineWidth = m.lineWidth || options.grid.markingsLineWidth;
  1585. ctx.moveTo(xrange.from, yrange.from);
  1586. ctx.lineTo(xrange.to, yrange.to);
  1587. ctx.stroke();
  1588. }
  1589. else {
  1590. // fill area
  1591. ctx.fillStyle = m.color || options.grid.markingsColor;
  1592. ctx.fillRect(xrange.from, yrange.to,
  1593. xrange.to - xrange.from,
  1594. yrange.from - yrange.to);
  1595. }
  1596. }
  1597. }
  1598. // draw the ticks
  1599. axes = allAxes();
  1600. bw = options.grid.borderWidth;
  1601. for (var j = 0; j < axes.length; ++j) {
  1602. var axis = axes[j], box = axis.box,
  1603. t = axis.tickLength, x, y, xoff, yoff;
  1604. if (!axis.show || axis.ticks.length == 0)
  1605. continue;
  1606. ctx.lineWidth = 1;
  1607. // find the edges
  1608. if (axis.direction == "x") {
  1609. x = 0;
  1610. if (t == "full")
  1611. y = (axis.position == "top" ? 0 : plotHeight);
  1612. else
  1613. y = box.top - plotOffset.top + (axis.position == "top" ? box.height : 0);
  1614. }
  1615. else {
  1616. y = 0;
  1617. if (t == "full")
  1618. x = (axis.position == "left" ? 0 : plotWidth);
  1619. else
  1620. x = box.left - plotOffset.left + (axis.position == "left" ? box.width : 0);
  1621. }
  1622. // draw tick bar
  1623. if (!axis.innermost) {
  1624. ctx.strokeStyle = axis.options.color;
  1625. ctx.beginPath();
  1626. xoff = yoff = 0;
  1627. if (axis.direction == "x")
  1628. xoff = plotWidth + 1;
  1629. else
  1630. yoff = plotHeight + 1;
  1631. if (ctx.lineWidth == 1) {
  1632. if (axis.direction == "x") {
  1633. y = Math.floor(y) + 0.5;
  1634. } else {
  1635. x = Math.floor(x) + 0.5;
  1636. }
  1637. }
  1638. ctx.moveTo(x, y);
  1639. ctx.lineTo(x + xoff, y + yoff);
  1640. ctx.stroke();
  1641. }
  1642. // draw ticks
  1643. ctx.strokeStyle = axis.options.tickColor;
  1644. ctx.beginPath();
  1645. for (i = 0; i < axis.ticks.length; ++i) {
  1646. var v = axis.ticks[i].v;
  1647. xoff = yoff = 0;
  1648. if (isNaN(v) || v < axis.min || v > axis.max
  1649. // skip those lying on the axes if we got a border
  1650. || (t == "full"
  1651. && ((typeof bw == "object" && bw[axis.position] > 0) || bw > 0)
  1652. && (v == axis.min || v == axis.max)))
  1653. continue;
  1654. if (axis.direction == "x") {
  1655. x = axis.p2c(v);
  1656. yoff = t == "full" ? -plotHeight : t;
  1657. if (axis.position == "top")
  1658. yoff = -yoff;
  1659. }
  1660. else {
  1661. y = axis.p2c(v);
  1662. xoff = t == "full" ? -plotWidth : t;
  1663. if (axis.position == "left")
  1664. xoff = -xoff;
  1665. }
  1666. if (ctx.lineWidth == 1) {
  1667. if (axis.direction == "x")
  1668. x = Math.floor(x) + 0.5;
  1669. else
  1670. y = Math.floor(y) + 0.5;
  1671. }
  1672. ctx.moveTo(x, y);
  1673. ctx.lineTo(x + xoff, y + yoff);
  1674. }
  1675. ctx.stroke();
  1676. }
  1677. // draw border
  1678. if (bw) {
  1679. // If either borderWidth or borderColor is an object, then draw the border
  1680. // line by line instead of as one rectangle
  1681. bc = options.grid.borderColor;
  1682. if(typeof bw == "object" || typeof bc == "object") {
  1683. if (typeof bw !== "object") {
  1684. bw = {top: bw, right: bw, bottom: bw, left: bw};
  1685. }
  1686. if (typeof bc !== "object") {
  1687. bc = {top: bc, right: bc, bottom: bc, left: bc};
  1688. }
  1689. if (bw.top > 0) {
  1690. ctx.strokeStyle = bc.top;
  1691. ctx.lineWidth = bw.top;
  1692. ctx.beginPath();
  1693. ctx.moveTo(0 - bw.left, 0 - bw.top/2);
  1694. ctx.lineTo(plotWidth, 0 - bw.top/2);
  1695. ctx.stroke();
  1696. }
  1697. if (bw.right > 0) {
  1698. ctx.strokeStyle = bc.right;
  1699. ctx.lineWidth = bw.right;
  1700. ctx.beginPath();
  1701. ctx.moveTo(plotWidth + bw.right / 2, 0 - bw.top);
  1702. ctx.lineTo(plotWidth + bw.right / 2, plotHeight);
  1703. ctx.stroke();
  1704. }
  1705. if (bw.bottom > 0) {
  1706. ctx.strokeStyle = bc.bottom;
  1707. ctx.lineWidth = bw.bottom;
  1708. ctx.beginPath();
  1709. ctx.moveTo(plotWidth + bw.right, plotHeight + bw.bottom / 2);
  1710. ctx.lineTo(0, plotHeight + bw.bottom / 2);
  1711. ctx.stroke();
  1712. }
  1713. if (bw.left > 0) {
  1714. ctx.strokeStyle = bc.left;
  1715. ctx.lineWidth = bw.left;
  1716. ctx.beginPath();
  1717. ctx.moveTo(0 - bw.left/2, plotHeight + bw.bottom);
  1718. ctx.lineTo(0- bw.left/2, 0);
  1719. ctx.stroke();
  1720. }
  1721. }
  1722. else {
  1723. ctx.lineWidth = bw;
  1724. ctx.strokeStyle = options.grid.borderColor;
  1725. ctx.strokeRect(-bw/2, -bw/2, plotWidth + bw, plotHeight + bw);
  1726. }
  1727. }
  1728. ctx.restore();
  1729. }
  1730. function drawAxisLabels() {
  1731. $.each(allAxes(), function (_, axis) {
  1732. var box = axis.box,
  1733. legacyStyles = axis.direction + "Axis " + axis.direction + axis.n + "Axis",
  1734. layer = "flot-" + axis.direction + "-axis flot-" + axis.direction + axis.n + "-axis " + legacyStyles,
  1735. font = axis.options.font || "flot-tick-label tickLabel",
  1736. tick, x, y, halign, valign;
  1737. // Remove text before checking for axis.show and ticks.length;
  1738. // otherwise plugins, like flot-tickrotor, that draw their own
  1739. // tick labels will end up with both theirs and the defaults.
  1740. surface.removeText(layer);
  1741. if (!axis.show || axis.ticks.length == 0)
  1742. return;
  1743. for (var i = 0; i < axis.ticks.length; ++i) {
  1744. tick = axis.ticks[i];
  1745. if (!tick.label || tick.v < axis.min || tick.v > axis.max)
  1746. continue;
  1747. if (axis.direction == "x") {
  1748. halign = "center";
  1749. x = plotOffset.left + axis.p2c(tick.v);
  1750. if (axis.position == "bottom") {
  1751. y = box.top + box.padding;
  1752. } else {
  1753. y = box.top + box.height - box.padding;
  1754. valign = "bottom";
  1755. }
  1756. } else {
  1757. valign = "middle";
  1758. y = plotOffset.top + axis.p2c(tick.v);
  1759. if (axis.position == "left") {
  1760. x = box.left + box.width - box.padding;
  1761. halign = "right";
  1762. } else {
  1763. x = box.left + box.padding;
  1764. }
  1765. }
  1766. surface.addText(layer, x, y, tick.label, font, null, null, halign, valign);
  1767. }
  1768. });
  1769. }
  1770. function drawSeries(series) {
  1771. if (series.lines.show)
  1772. drawSeriesLines(series);
  1773. if (series.bars.show)
  1774. drawSeriesBars(series);
  1775. if (series.points.show)
  1776. drawSeriesPoints(series);
  1777. }
  1778. function drawSeriesLines(series) {
  1779. function plotLine(datapoints, xoffset, yoffset, axisx, axisy) {
  1780. var points = datapoints.points,
  1781. ps = datapoints.pointsize,
  1782. prevx = null, prevy = null;
  1783. ctx.beginPath();
  1784. for (var i = ps; i < points.length; i += ps) {
  1785. var x1 = points[i - ps], y1 = points[i - ps + 1],
  1786. x2 = points[i], y2 = points[i + 1];
  1787. if (x1 == null || x2 == null)
  1788. continue;
  1789. // clip with ymin
  1790. if (y1 <= y2 && y1 < axisy.min) {
  1791. if (y2 < axisy.min)
  1792. continue; // line segment is outside
  1793. // compute new intersection point
  1794. x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
  1795. y1 = axisy.min;
  1796. }
  1797. else if (y2 <= y1 && y2 < axisy.min) {
  1798. if (y1 < axisy.min)
  1799. continue;
  1800. x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
  1801. y2 = axisy.min;
  1802. }
  1803. // clip with ymax
  1804. if (y1 >= y2 && y1 > axisy.max) {
  1805. if (y2 > axisy.max)
  1806. continue;
  1807. x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
  1808. y1 = axisy.max;
  1809. }
  1810. else if (y2 >= y1 && y2 > axisy.max) {
  1811. if (y1 > axisy.max)
  1812. continue;
  1813. x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
  1814. y2 = axisy.max;
  1815. }
  1816. // clip with xmin
  1817. if (x1 <= x2 && x1 < axisx.min) {
  1818. if (x2 < axisx.min)
  1819. continue;
  1820. y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
  1821. x1 = axisx.min;
  1822. }
  1823. else if (x2 <= x1 && x2 < axisx.min) {
  1824. if (x1 < axisx.min)
  1825. continue;
  1826. y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
  1827. x2 = axisx.min;
  1828. }
  1829. // clip with xmax
  1830. if (x1 >= x2 && x1 > axisx.max) {
  1831. if (x2 > axisx.max)
  1832. continue;
  1833. y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
  1834. x1 = axisx.max;
  1835. }
  1836. else if (x2 >= x1 && x2 > axisx.max) {
  1837. if (x1 > axisx.max)
  1838. continue;
  1839. y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
  1840. x2 = axisx.max;
  1841. }
  1842. if (x1 != prevx || y1 != prevy)
  1843. ctx.moveTo(axisx.p2c(x1) + xoffset, axisy.p2c(y1) + yoffset);
  1844. prevx = x2;
  1845. prevy = y2;
  1846. ctx.lineTo(axisx.p2c(x2) + xoffset, axisy.p2c(y2) + yoffset);
  1847. }
  1848. ctx.stroke();
  1849. }
  1850. function plotLineArea(datapoints, axisx, axisy) {
  1851. var points = datapoints.points,
  1852. ps = datapoints.pointsize,
  1853. bottom = Math.min(Math.max(0, axisy.min), axisy.max),
  1854. i = 0, top, areaOpen = false,
  1855. ypos = 1, segmentStart = 0, segmentEnd = 0;
  1856. // we process each segment in two turns, first forward
  1857. // direction to sketch out top, then once we hit the
  1858. // end we go backwards to sketch the bottom
  1859. while (true) {
  1860. if (ps > 0 && i > points.length + ps)
  1861. break;
  1862. i += ps; // ps is negative if going backwards
  1863. var x1 = points[i - ps],
  1864. y1 = points[i - ps + ypos],
  1865. x2 = points[i], y2 = points[i + ypos];
  1866. if (areaOpen) {
  1867. if (ps > 0 && x1 != null && x2 == null) {
  1868. // at turning point
  1869. segmentEnd = i;
  1870. ps = -ps;
  1871. ypos = 2;
  1872. continue;
  1873. }
  1874. if (ps < 0 && i == segmentStart + ps) {
  1875. // done with the reverse sweep
  1876. ctx.fill();
  1877. areaOpen = false;
  1878. ps = -ps;
  1879. ypos = 1;
  1880. i = segmentStart = segmentEnd + ps;
  1881. continue;
  1882. }
  1883. }
  1884. if (x1 == null || x2 == null)
  1885. continue;
  1886. // clip x values
  1887. // clip with xmin
  1888. if (x1 <= x2 && x1 < axisx.min) {
  1889. if (x2 < axisx.min)
  1890. continue;
  1891. y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
  1892. x1 = axisx.min;
  1893. }
  1894. else if (x2 <= x1 && x2 < axisx.min) {
  1895. if (x1 < axisx.min)
  1896. continue;
  1897. y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
  1898. x2 = axisx.min;
  1899. }
  1900. // clip with xmax
  1901. if (x1 >= x2 && x1 > axisx.max) {
  1902. if (x2 > axisx.max)
  1903. continue;
  1904. y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
  1905. x1 = axisx.max;
  1906. }
  1907. else if (x2 >= x1 && x2 > axisx.max) {
  1908. if (x1 > axisx.max)
  1909. continue;
  1910. y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
  1911. x2 = axisx.max;
  1912. }
  1913. if (!areaOpen) {
  1914. // open area
  1915. ctx.beginPath();
  1916. ctx.moveTo(axisx.p2c(x1), axisy.p2c(bottom));
  1917. areaOpen = true;
  1918. }
  1919. // now first check the case where both is outside
  1920. if (y1 >= axisy.max && y2 >= axisy.max) {
  1921. ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.max));
  1922. ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.max));
  1923. continue;
  1924. }
  1925. else if (y1 <= axisy.min && y2 <= axisy.min) {
  1926. ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.min));
  1927. ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.min));
  1928. continue;
  1929. }
  1930. // else it's a bit more complicated, there might
  1931. // be a flat maxed out rectangle first, then a
  1932. // triangular cutout or reverse; to find these
  1933. // keep track of the current x values
  1934. var x1old = x1, x2old = x2;
  1935. // clip the y values, without shortcutting, we
  1936. // go through all cases in turn
  1937. // clip with ymin
  1938. if (y1 <= y2 && y1 < axisy.min && y2 >= axisy.min) {
  1939. x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
  1940. y1 = axisy.min;
  1941. }
  1942. else if (y2 <= y1 && y2 < axisy.min && y1 >= axisy.min) {
  1943. x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
  1944. y2 = axisy.min;
  1945. }
  1946. // clip with ymax
  1947. if (y1 >= y2 && y1 > axisy.max && y2 <= axisy.max) {
  1948. x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
  1949. y1 = axisy.max;
  1950. }
  1951. else if (y2 >= y1 && y2 > axisy.max && y1 <= axisy.max) {
  1952. x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
  1953. y2 = axisy.max;
  1954. }
  1955. // if the x value was changed we got a rectangle
  1956. // to fill
  1957. if (x1 != x1old) {
  1958. ctx.lineTo(axisx.p2c(x1old), axisy.p2c(y1));
  1959. // it goes to (x1, y1), but we fill that below
  1960. }
  1961. // fill triangular section, this sometimes result
  1962. // in redundant points if (x1, y1) hasn't changed
  1963. // from previous line to, but we just ignore that
  1964. ctx.lineTo(axisx.p2c(x1), axisy.p2c(y1));
  1965. ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2));
  1966. // fill the other rectangle if it's there
  1967. if (x2 != x2old) {
  1968. ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2));
  1969. ctx.lineTo(axisx.p2c(x2old), axisy.p2c(y2));
  1970. }
  1971. }
  1972. }
  1973. ctx.save();
  1974. ctx.translate(plotOffset.left, plotOffset.top);
  1975. ctx.lineJoin = "round";
  1976. var lw = series.lines.lineWidth,
  1977. sw = series.shadowSize;
  1978. // FIXME: consider another form of shadow when filling is turned on
  1979. if (lw > 0 && sw > 0) {
  1980. // draw shadow as a thick and thin line with transparency
  1981. ctx.lineWidth = sw;
  1982. ctx.strokeStyle = "rgba(0,0,0,0.1)";
  1983. // position shadow at angle from the mid of line
  1984. var angle = Math.PI/18;
  1985. plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/2), Math.cos(angle) * (lw/2 + sw/2), series.xaxis, series.yaxis);
  1986. ctx.lineWidth = sw/2;
  1987. plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/4), Math.cos(angle) * (lw/2 + sw/4), series.xaxis, series.yaxis);
  1988. }
  1989. ctx.lineWidth = lw;
  1990. ctx.strokeStyle = series.color;
  1991. var fillStyle = getFillStyle(series.lines, series.color, 0, plotHeight);
  1992. if (fillStyle) {
  1993. ctx.fillStyle = fillStyle;
  1994. plotLineArea(series.datapoints, series.xaxis, series.yaxis);
  1995. }
  1996. if (lw > 0)
  1997. plotLine(series.datapoints, 0, 0, series.xaxis, series.yaxis);
  1998. ctx.restore();
  1999. }
  2000. function drawSeriesPoints(series) {
  2001. function plotPoints(datapoints, radius, fillStyle, offset, shadow, axisx, axisy, symbol) {
  2002. var points = datapoints.points, ps = datapoints.pointsize;
  2003. for (var i = 0; i < points.length; i += ps) {
  2004. var x = points[i], y = points[i + 1];
  2005. if (x == null || x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max)
  2006. continue;
  2007. ctx.beginPath();
  2008. x = axisx.p2c(x);
  2009. y = axisy.p2c(y) + offset;
  2010. if (symbol == "circle")
  2011. ctx.arc(x, y, radius, 0, shadow ? Math.PI : Math.PI * 2, false);
  2012. else
  2013. symbol(ctx, x, y, radius, shadow);
  2014. ctx.closePath();
  2015. if (fillStyle) {
  2016. ctx.fillStyle = fillStyle;
  2017. ctx.fill();
  2018. }
  2019. ctx.stroke();
  2020. }
  2021. }
  2022. ctx.save();
  2023. ctx.translate(plotOffset.left, plotOffset.top);
  2024. var lw = series.points.lineWidth,
  2025. sw = series.shadowSize,
  2026. radius = series.points.radius,
  2027. symbol = series.points.symbol;
  2028. // If the user sets the line width to 0, we change it to a very
  2029. // small value. A line width of 0 seems to force the default of 1.
  2030. // Doing the conditional here allows the shadow setting to still be
  2031. // optional even with a lineWidth of 0.
  2032. if( lw == 0 )
  2033. lw = 0.0001;
  2034. if (lw > 0 && sw > 0) {
  2035. // draw shadow in two steps
  2036. var w = sw / 2;
  2037. ctx.lineWidth = w;
  2038. ctx.strokeStyle = "rgba(0,0,0,0.1)";
  2039. plotPoints(series.datapoints, radius, null, w + w/2, true,
  2040. series.xaxis, series.yaxis, symbol);
  2041. ctx.strokeStyle = "rgba(0,0,0,0.2)";
  2042. plotPoints(series.datapoints, radius, null, w/2, true,
  2043. series.xaxis, series.yaxis, symbol);
  2044. }
  2045. ctx.lineWidth = lw;
  2046. ctx.strokeStyle = series.color;
  2047. plotPoints(series.datapoints, radius,
  2048. getFillStyle(series.points, series.color), 0, false,
  2049. series.xaxis, series.yaxis, symbol);
  2050. ctx.restore();
  2051. }
  2052. function drawBar(x, y, b, barLeft, barRight, fillStyleCallback, axisx, axisy, c, horizontal, lineWidth) {
  2053. var left, right, bottom, top,
  2054. drawLeft, drawRight, drawTop, drawBottom,
  2055. tmp;
  2056. // in horizontal mode, we start the bar from the left
  2057. // instead of from the bottom so it appears to be
  2058. // horizontal rather than vertical
  2059. if (horizontal) {
  2060. drawBottom = drawRight = drawTop = true;
  2061. drawLeft = false;
  2062. left = b;
  2063. right = x;
  2064. top = y + barLeft;
  2065. bottom = y + barRight;
  2066. // account for negative bars
  2067. if (right < left) {
  2068. tmp = right;
  2069. right = left;
  2070. left = tmp;
  2071. drawLeft = true;
  2072. drawRight = false;
  2073. }
  2074. }
  2075. else {
  2076. drawLeft = drawRight = drawTop = true;
  2077. drawBottom = false;
  2078. left = x + barLeft;
  2079. right = x + barRight;
  2080. bottom = b;
  2081. top = y;
  2082. // account for negative bars
  2083. if (top < bottom) {
  2084. tmp = top;
  2085. top = bottom;
  2086. bottom = tmp;
  2087. drawBottom = true;
  2088. drawTop = false;
  2089. }
  2090. }
  2091. // clip
  2092. if (right < axisx.min || left > axisx.max ||
  2093. top < axisy.min || bottom > axisy.max)
  2094. return;
  2095. if (left < axisx.min) {
  2096. left = axisx.min;
  2097. drawLeft = false;
  2098. }
  2099. if (right > axisx.max) {
  2100. right = axisx.max;
  2101. drawRight = false;
  2102. }
  2103. if (bottom < axisy.min) {
  2104. bottom = axisy.min;
  2105. drawBottom = false;
  2106. }
  2107. if (top > axisy.max) {
  2108. top = axisy.max;
  2109. drawTop = false;
  2110. }
  2111. left = axisx.p2c(left);
  2112. bottom = axisy.p2c(bottom);
  2113. right = axisx.p2c(right);
  2114. top = axisy.p2c(top);
  2115. // fill the bar
  2116. if (fillStyleCallback) {
  2117. c.fillStyle = fillStyleCallback(bottom, top);
  2118. c.fillRect(left, top, right - left, bottom - top)
  2119. }
  2120. // draw outline
  2121. if (lineWidth > 0 && (drawLeft || drawRight || drawTop || drawBottom)) {
  2122. c.beginPath();
  2123. // FIXME: inline moveTo is buggy with excanvas
  2124. c.moveTo(left, bottom);
  2125. if (drawLeft)
  2126. c.lineTo(left, top);
  2127. else
  2128. c.moveTo(left, top);
  2129. if (drawTop)
  2130. c.lineTo(right, top);
  2131. else
  2132. c.moveTo(right, top);
  2133. if (drawRight)
  2134. c.lineTo(right, bottom);
  2135. else
  2136. c.moveTo(right, bottom);
  2137. if (drawBottom)
  2138. c.lineTo(left, bottom);
  2139. else
  2140. c.moveTo(left, bottom);
  2141. c.stroke();
  2142. }
  2143. }
  2144. function drawSeriesBars(series) {
  2145. function plotBars(datapoints, barLeft, barRight, fillStyleCallback, axisx, axisy) {
  2146. var points = datapoints.points, ps = datapoints.pointsize;
  2147. for (var i = 0; i < points.length; i += ps) {
  2148. if (points[i] == null)
  2149. continue;
  2150. drawBar(points[i], points[i + 1], points[i + 2], barLeft, barRight, fillStyleCallback, axisx, axisy, ctx, series.bars.horizontal, series.bars.lineWidth);
  2151. }
  2152. }
  2153. ctx.save();
  2154. ctx.translate(plotOffset.left, plotOffset.top);
  2155. // FIXME: figure out a way to add shadows (for instance along the right edge)
  2156. ctx.lineWidth = series.bars.lineWidth;
  2157. ctx.strokeStyle = series.color;
  2158. var barLeft;
  2159. switch (series.bars.align) {
  2160. case "left":
  2161. barLeft = 0;
  2162. break;
  2163. case "right":
  2164. barLeft = -series.bars.barWidth;
  2165. break;
  2166. default:
  2167. barLeft = -series.bars.barWidth / 2;
  2168. }
  2169. var fillStyleCallback = series.bars.fill ? function (bottom, top) { return getFillStyle(series.bars, series.color, bottom, top); } : null;
  2170. plotBars(series.datapoints, barLeft, barLeft + series.bars.barWidth, fillStyleCallback, series.xaxis, series.yaxis);
  2171. ctx.restore();
  2172. }
  2173. function getFillStyle(filloptions, seriesColor, bottom, top) {
  2174. var fill = filloptions.fill;
  2175. if (!fill)
  2176. return null;
  2177. if (filloptions.fillColor)
  2178. return getColorOrGradient(filloptions.fillColor, bottom, top, seriesColor);
  2179. var c = $.color.parse(seriesColor);
  2180. c.a = typeof fill == "number" ? fill : 0.4;
  2181. c.normalize();
  2182. return c.toString();
  2183. }
  2184. function insertLegend() {
  2185. placeholder.find(".legend").remove();
  2186. if (!options.legend.show)
  2187. return;
  2188. var fragments = [], entries = [], rowStarted = false,
  2189. lf = options.legend.labelFormatter, s, label;
  2190. // Build a list of legend entries, with each having a label and a color
  2191. for (var i = 0; i < series.length; ++i) {
  2192. s = series[i];
  2193. if (s.label) {
  2194. label = lf ? lf(s.label, s) : s.label;
  2195. if (label) {
  2196. entries.push({
  2197. label: label,
  2198. color: s.color
  2199. });
  2200. }
  2201. }
  2202. }
  2203. // Sort the legend using either the default or a custom comparator
  2204. if (options.legend.sorted) {
  2205. if ($.isFunction(options.legend.sorted)) {
  2206. entries.sort(options.legend.sorted);
  2207. } else if (options.legend.sorted == "reverse") {
  2208. entries.reverse();
  2209. } else {
  2210. var ascending = options.legend.sorted != "descending";
  2211. entries.sort(function(a, b) {
  2212. return a.label == b.label ? 0 : (
  2213. (a.label < b.label) != ascending ? 1 : -1 // Logical XOR
  2214. );
  2215. });
  2216. }
  2217. }
  2218. // Generate markup for the list of entries, in their final order
  2219. for (var i = 0; i < entries.length; ++i) {
  2220. var entry = entries[i];
  2221. if (i % options.legend.noColumns == 0) {
  2222. if (rowStarted)
  2223. fragments.push('</tr>');
  2224. fragments.push('<tr>');
  2225. rowStarted = true;
  2226. }
  2227. fragments.push(
  2228. '<td class="legendColorBox"><div style="border:1px solid ' + options.legend.labelBoxBorderColor + ';padding:1px"><div style="width:4px;height:0;border:5px solid ' + entry.color + ';overflow:hidden"></div></div></td>' +
  2229. '<td class="legendLabel">' + entry.label + '</td>'
  2230. );
  2231. }
  2232. if (rowStarted)
  2233. fragments.push('</tr>');
  2234. if (fragments.length == 0)
  2235. return;
  2236. var table = '<table style="font-size:smaller;color: #FFF;">' + fragments.join("") + '</table>';
  2237. if (options.legend.container != null)
  2238. $(options.legend.container).html(table);
  2239. else {
  2240. var pos = "",
  2241. p = options.legend.position,
  2242. m = options.legend.margin;
  2243. if (m[0] == null)
  2244. m = [m, m];
  2245. if (p.charAt(0) == "n")
  2246. pos += 'top:' + (m[1] + plotOffset.top) + 'px;';
  2247. else if (p.charAt(0) == "s")
  2248. pos += 'bottom:' + (m[1] + plotOffset.bottom) + 'px;';
  2249. if (p.charAt(1) == "e")
  2250. pos += 'right:' + (m[0] + plotOffset.right) + 'px;';
  2251. else if (p.charAt(1) == "w")
  2252. pos += 'left:' + (m[0] + plotOffset.left) + 'px;';
  2253. var legend = $('<div class="legend">' + table.replace('style="', 'style="position:absolute;' + pos +';') + '</div>').appendTo(placeholder);
  2254. if (options.legend.backgroundOpacity != 0.0) {
  2255. // put in the transparent background
  2256. // separately to avoid blended labels and
  2257. // label boxes
  2258. var c = options.legend.backgroundColor;
  2259. if (c == null) {
  2260. c = options.grid.backgroundColor;
  2261. if (c && typeof c == "string")
  2262. c = $.color.parse(c);
  2263. else
  2264. c = $.color.extract(legend, 'background-color');
  2265. c.a = 1;
  2266. c = c.toString();
  2267. }
  2268. var div = legend.children();
  2269. $('<div style="position:absolute;width:' + div.width() + 'px;height:' + div.height() + 'px;' + pos +'background-color:' + c + ';"> </div>').prependTo(legend).css('opacity', options.legend.backgroundOpacity);
  2270. }
  2271. }
  2272. }
  2273. // interactive features
  2274. var highlights = [],
  2275. redrawTimeout = null;
  2276. // returns the data item the mouse is over, or null if none is found
  2277. function findNearbyItem(mouseX, mouseY, seriesFilter) {
  2278. var maxDistance = options.grid.mouseActiveRadius,
  2279. smallestDistance = maxDistance * maxDistance + 1,
  2280. item = null, foundPoint = false, i, j, ps;
  2281. for (i = series.length - 1; i >= 0; --i) {
  2282. if (!seriesFilter(series[i]))
  2283. continue;
  2284. var s = series[i],
  2285. axisx = s.xaxis,
  2286. axisy = s.yaxis,
  2287. points = s.datapoints.points,
  2288. mx = axisx.c2p(mouseX), // precompute some stuff to make the loop faster
  2289. my = axisy.c2p(mouseY),
  2290. maxx = maxDistance / axisx.scale,
  2291. maxy = maxDistance / axisy.scale;
  2292. ps = s.datapoints.pointsize;
  2293. // with inverse transforms, we can't use the maxx/maxy
  2294. // optimization, sadly
  2295. if (axisx.options.inverseTransform)
  2296. maxx = Number.MAX_VALUE;
  2297. if (axisy.options.inverseTransform)
  2298. maxy = Number.MAX_VALUE;
  2299. if (s.lines.show || s.points.show) {
  2300. for (j = 0; j < points.length; j += ps) {
  2301. var x = points[j], y = points[j + 1];
  2302. if (x == null)
  2303. continue;
  2304. // For points and lines, the cursor must be within a
  2305. // certain distance to the data point
  2306. if (x - mx > maxx || x - mx < -maxx ||
  2307. y - my > maxy || y - my < -maxy)
  2308. continue;
  2309. // We have to calculate distances in pixels, not in
  2310. // data units, because the scales of the axes may be different
  2311. var dx = Math.abs(axisx.p2c(x) - mouseX),
  2312. dy = Math.abs(axisy.p2c(y) - mouseY),
  2313. dist = dx * dx + dy * dy; // we save the sqrt
  2314. // use <= to ensure last point takes precedence
  2315. // (last generally means on top of)
  2316. if (dist < smallestDistance) {
  2317. smallestDistance = dist;
  2318. item = [i, j / ps];
  2319. }
  2320. }
  2321. }
  2322. if (s.bars.show && !item) { // no other point can be nearby
  2323. var barLeft, barRight;
  2324. switch (s.bars.align) {
  2325. case "left":
  2326. barLeft = 0;
  2327. break;
  2328. case "right":
  2329. barLeft = -s.bars.barWidth;
  2330. break;
  2331. default:
  2332. barLeft = -s.bars.barWidth / 2;
  2333. }
  2334. barRight = barLeft + s.bars.barWidth;
  2335. for (j = 0; j < points.length; j += ps) {
  2336. var x = points[j], y = points[j + 1], b = points[j + 2];
  2337. if (x == null)
  2338. continue;
  2339. // for a bar graph, the cursor must be inside the bar
  2340. if (series[i].bars.horizontal ?
  2341. (mx <= Math.max(b, x) && mx >= Math.min(b, x) &&
  2342. my >= y + barLeft && my <= y + barRight) :
  2343. (mx >= x + barLeft && mx <= x + barRight &&
  2344. my >= Math.min(b, y) && my <= Math.max(b, y)))
  2345. item = [i, j / ps];
  2346. }
  2347. }
  2348. }
  2349. if (item) {
  2350. i = item[0];
  2351. j = item[1];
  2352. ps = series[i].datapoints.pointsize;
  2353. return { datapoint: series[i].datapoints.points.slice(j * ps, (j + 1) * ps),
  2354. dataIndex: j,
  2355. series: series[i],
  2356. seriesIndex: i };
  2357. }
  2358. return null;
  2359. }
  2360. function onMouseMove(e) {
  2361. if (options.grid.hoverable)
  2362. triggerClickHoverEvent("plothover", e,
  2363. function (s) { return s["hoverable"] != false; });
  2364. }
  2365. function onMouseLeave(e) {
  2366. if (options.grid.hoverable)
  2367. triggerClickHoverEvent("plothover", e,
  2368. function (s) { return false; });
  2369. }
  2370. function onClick(e) {
  2371. triggerClickHoverEvent("plotclick", e,
  2372. function (s) { return s["clickable"] != false; });
  2373. }
  2374. // trigger click or hover event (they send the same parameters
  2375. // so we share their code)
  2376. function triggerClickHoverEvent(eventname, event, seriesFilter) {
  2377. var offset = eventHolder.offset(),
  2378. canvasX = event.pageX - offset.left - plotOffset.left,
  2379. canvasY = event.pageY - offset.top - plotOffset.top,
  2380. pos = canvasToAxisCoords({ left: canvasX, top: canvasY });
  2381. pos.pageX = event.pageX;
  2382. pos.pageY = event.pageY;
  2383. var item = findNearbyItem(canvasX, canvasY, seriesFilter);
  2384. if (item) {
  2385. // fill in mouse pos for any listeners out there
  2386. item.pageX = parseInt(item.series.xaxis.p2c(item.datapoint[0]) + offset.left + plotOffset.left, 10);
  2387. item.pageY = parseInt(item.series.yaxis.p2c(item.datapoint[1]) + offset.top + plotOffset.top, 10);
  2388. }
  2389. if (options.grid.autoHighlight) {
  2390. // clear auto-highlights
  2391. for (var i = 0; i < highlights.length; ++i) {
  2392. var h = highlights[i];
  2393. if (h.auto == eventname &&
  2394. !(item && h.series == item.series &&
  2395. h.point[0] == item.datapoint[0] &&
  2396. h.point[1] == item.datapoint[1]))
  2397. unhighlight(h.series, h.point);
  2398. }
  2399. if (item)
  2400. highlight(item.series, item.datapoint, eventname);
  2401. }
  2402. placeholder.trigger(eventname, [ pos, item ]);
  2403. }
  2404. function triggerRedrawOverlay() {
  2405. var t = options.interaction.redrawOverlayInterval;
  2406. if (t == -1) { // skip event queue
  2407. drawOverlay();
  2408. return;
  2409. }
  2410. if (!redrawTimeout)
  2411. redrawTimeout = setTimeout(drawOverlay, t);
  2412. }
  2413. function drawOverlay() {
  2414. redrawTimeout = null;
  2415. // draw highlights
  2416. octx.save();
  2417. overlay.clear();
  2418. octx.translate(plotOffset.left, plotOffset.top);
  2419. var i, hi;
  2420. for (i = 0; i < highlights.length; ++i) {
  2421. hi = highlights[i];
  2422. if (hi.series.bars.show)
  2423. drawBarHighlight(hi.series, hi.point);
  2424. else
  2425. drawPointHighlight(hi.series, hi.point);
  2426. }
  2427. octx.restore();
  2428. executeHooks(hooks.drawOverlay, [octx]);
  2429. }
  2430. function highlight(s, point, auto) {
  2431. if (typeof s == "number")
  2432. s = series[s];
  2433. if (typeof point == "number") {
  2434. var ps = s.datapoints.pointsize;
  2435. point = s.datapoints.points.slice(ps * point, ps * (point + 1));
  2436. }
  2437. var i = indexOfHighlight(s, point);
  2438. if (i == -1) {
  2439. highlights.push({ series: s, point: point, auto: auto });
  2440. triggerRedrawOverlay();
  2441. }
  2442. else if (!auto)
  2443. highlights[i].auto = false;
  2444. }
  2445. function unhighlight(s, point) {
  2446. if (s == null && point == null) {
  2447. highlights = [];
  2448. triggerRedrawOverlay();
  2449. return;
  2450. }
  2451. if (typeof s == "number")
  2452. s = series[s];
  2453. if (typeof point == "number") {
  2454. var ps = s.datapoints.pointsize;
  2455. point = s.datapoints.points.slice(ps * point, ps * (point + 1));
  2456. }
  2457. var i = indexOfHighlight(s, point);
  2458. if (i != -1) {
  2459. highlights.splice(i, 1);
  2460. triggerRedrawOverlay();
  2461. }
  2462. }
  2463. function indexOfHighlight(s, p) {
  2464. for (var i = 0; i < highlights.length; ++i) {
  2465. var h = highlights[i];
  2466. if (h.series == s && h.point[0] == p[0]
  2467. && h.point[1] == p[1])
  2468. return i;
  2469. }
  2470. return -1;
  2471. }
  2472. function drawPointHighlight(series, point) {
  2473. var x = point[0], y = point[1],
  2474. axisx = series.xaxis, axisy = series.yaxis,
  2475. highlightColor = (typeof series.highlightColor === "string") ? series.highlightColor : $.color.parse(series.color).scale('a', 0.5).toString();
  2476. if (x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max)
  2477. return;
  2478. var pointRadius = series.points.radius + series.points.lineWidth / 2;
  2479. octx.lineWidth = pointRadius;
  2480. octx.strokeStyle = highlightColor;
  2481. var radius = 1.5 * pointRadius;
  2482. x = axisx.p2c(x);
  2483. y = axisy.p2c(y);
  2484. octx.beginPath();
  2485. if (series.points.symbol == "circle")
  2486. octx.arc(x, y, radius, 0, 2 * Math.PI, false);
  2487. else
  2488. series.points.symbol(octx, x, y, radius, false);
  2489. octx.closePath();
  2490. octx.stroke();
  2491. }
  2492. function drawBarHighlight(series, point) {
  2493. var highlightColor = (typeof series.highlightColor === "string") ? series.highlightColor : $.color.parse(series.color).scale('a', 0.5).toString(),
  2494. fillStyle = highlightColor,
  2495. barLeft;
  2496. switch (series.bars.align) {
  2497. case "left":
  2498. barLeft = 0;
  2499. break;
  2500. case "right":
  2501. barLeft = -series.bars.barWidth;
  2502. break;
  2503. default:
  2504. barLeft = -series.bars.barWidth / 2;
  2505. }
  2506. octx.lineWidth = series.bars.lineWidth;
  2507. octx.strokeStyle = highlightColor;
  2508. drawBar(point[0], point[1], point[2] || 0, barLeft, barLeft + series.bars.barWidth,
  2509. function () { return fillStyle; }, series.xaxis, series.yaxis, octx, series.bars.horizontal, series.bars.lineWidth);
  2510. }
  2511. function getColorOrGradient(spec, bottom, top, defaultColor) {
  2512. if (typeof spec == "string")
  2513. return spec;
  2514. else {
  2515. // assume this is a gradient spec; IE currently only
  2516. // supports a simple vertical gradient properly, so that's
  2517. // what we support too
  2518. var gradient = ctx.createLinearGradient(0, top, 0, bottom);
  2519. for (var i = 0, l = spec.colors.length; i < l; ++i) {
  2520. var c = spec.colors[i];
  2521. if (typeof c != "string") {
  2522. var co = $.color.parse(defaultColor);
  2523. if (c.brightness != null)
  2524. co = co.scale('rgb', c.brightness);
  2525. if (c.opacity != null)
  2526. co.a *= c.opacity;
  2527. c = co.toString();
  2528. }
  2529. gradient.addColorStop(i / (l - 1), c);
  2530. }
  2531. return gradient;
  2532. }
  2533. }
  2534. }
  2535. // Add the plot function to the top level of the jQuery object
  2536. $.plot = function(placeholder, data, options) {
  2537. //var t0 = new Date();
  2538. var plot = new Plot($(placeholder), data, options, $.plot.plugins);
  2539. //(window.console ? console.log : alert)("time used (msecs): " + ((new Date()).getTime() - t0.getTime()));
  2540. return plot;
  2541. };
  2542. $.plot.version = "0.8.2-alpha";
  2543. $.plot.plugins = [];
  2544. // Also add the plot function as a chainable property
  2545. $.fn.plot = function(data, options) {
  2546. return this.each(function() {
  2547. $.plot(this, data, options);
  2548. });
  2549. };
  2550. // round to nearby lower multiple of base
  2551. function floorInBase(n, base) {
  2552. return base * Math.floor(n / base);
  2553. }
  2554. })(jQuery);