jquery.flot.js 121 KB

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