jquery.flot.js 113 KB

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