jquery.flot.js 119 KB

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