jquery.flot.js 116 KB

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