jquery.flot.js 124 KB

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