jquery.flot.js 124 KB

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