jquery.flot.js 107 KB

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