jquery.flot.js 120 KB

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