jquery.flot.js 116 KB

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