jquery.flot.js 121 KB

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