jquery.flot.js 120 KB

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