jquery.flot.js 121 KB

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