jquery.flot.js 116 KB

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