jquery.flot.js 107 KB

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