jquery.flot.js 121 KB

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