smoothie.js 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110
  1. // MIT License:
  2. //
  3. // Copyright (c) 2010-2013, Joe Walnes
  4. // 2013-2018, Drew Noakes
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. /**
  24. * Smoothie Charts - http://smoothiecharts.org/
  25. * (c) 2010-2013, Joe Walnes
  26. * 2013-2018, Drew Noakes
  27. *
  28. * v1.0: Main charting library, by Joe Walnes
  29. * v1.1: Auto scaling of axis, by Neil Dunn
  30. * v1.2: fps (frames per second) option, by Mathias Petterson
  31. * v1.3: Fix for divide by zero, by Paul Nikitochkin
  32. * v1.4: Set minimum, top-scale padding, remove timeseries, add optional timer to reset bounds, by Kelley Reynolds
  33. * v1.5: Set default frames per second to 50... smoother.
  34. * .start(), .stop() methods for conserving CPU, by Dmitry Vyal
  35. * options.interpolation = 'bezier' or 'line', by Dmitry Vyal
  36. * options.maxValue to fix scale, by Dmitry Vyal
  37. * v1.6: minValue/maxValue will always get converted to floats, by Przemek Matylla
  38. * v1.7: options.grid.fillStyle may be a transparent color, by Dmitry A. Shashkin
  39. * Smooth rescaling, by Kostas Michalopoulos
  40. * v1.8: Set max length to customize number of live points in the dataset with options.maxDataSetLength, by Krishna Narni
  41. * v1.9: Display timestamps along the bottom, by Nick and Stev-io
  42. * (https://groups.google.com/forum/?fromgroups#!topic/smoothie-charts/-Ywse8FCpKI%5B1-25%5D)
  43. * Refactored by Krishna Narni, to support timestamp formatting function
  44. * v1.10: Switch to requestAnimationFrame, removed the now obsoleted options.fps, by Gergely Imreh
  45. * v1.11: options.grid.sharpLines option added, by @drewnoakes
  46. * Addressed warning seen in Firefox when seriesOption.fillStyle undefined, by @drewnoakes
  47. * v1.12: Support for horizontalLines added, by @drewnoakes
  48. * Support for yRangeFunction callback added, by @drewnoakes
  49. * v1.13: Fixed typo (#32), by @alnikitich
  50. * v1.14: Timer cleared when last TimeSeries removed (#23), by @davidgaleano
  51. * Fixed diagonal line on chart at start/end of data stream, by @drewnoakes
  52. * v1.15: Support for npm package (#18), by @dominictarr
  53. * Fixed broken removeTimeSeries function (#24) by @davidgaleano
  54. * Minor performance and tidying, by @drewnoakes
  55. * v1.16: Bug fix introduced in v1.14 relating to timer creation/clearance (#23), by @drewnoakes
  56. * TimeSeries.append now deals with out-of-order timestamps, and can merge duplicates, by @zacwitte (#12)
  57. * Documentation and some local variable renaming for clarity, by @drewnoakes
  58. * v1.17: Allow control over font size (#10), by @drewnoakes
  59. * Timestamp text won't overlap, by @drewnoakes
  60. * v1.18: Allow control of max/min label precision, by @drewnoakes
  61. * Added 'borderVisible' chart option, by @drewnoakes
  62. * Allow drawing series with fill but no stroke (line), by @drewnoakes
  63. * v1.19: Avoid unnecessary repaints, and fixed flicker in old browsers having multiple charts in document (#40), by @asbai
  64. * v1.20: Add SmoothieChart.getTimeSeriesOptions and SmoothieChart.bringToFront functions, by @drewnoakes
  65. * v1.21: Add 'step' interpolation mode, by @drewnoakes
  66. * v1.22: Add support for different pixel ratios. Also add optional y limit formatters, by @copacetic
  67. * v1.23: Fix bug introduced in v1.22 (#44), by @drewnoakes
  68. * v1.24: Fix bug introduced in v1.23, re-adding parseFloat to y-axis formatter defaults, by @siggy_sf
  69. * v1.25: Fix bug seen when adding a data point to TimeSeries which is older than the current data, by @Nking92
  70. * Draw time labels on top of series, by @comolosabia
  71. * Add TimeSeries.clear function, by @drewnoakes
  72. * v1.26: Add support for resizing on high device pixel ratio screens, by @copacetic
  73. * v1.27: Fix bug introduced in v1.26 for non whole number devicePixelRatio values, by @zmbush
  74. * v1.28: Add 'minValueScale' option, by @megawac
  75. * Fix 'labelPos' for different size of 'minValueString' 'maxValueString', by @henryn
  76. * v1.29: Support responsive sizing, by @drewnoakes
  77. * v1.29.1: Include types in package, and make property optional, by @TrentHouliston
  78. * v1.30: Fix inverted logic in devicePixelRatio support, by @scanlime
  79. * v1.31: Support tooltips, by @Sly1024 and @drewnoakes
  80. * v1.32: Support frame rate limit, by @dpuyosa
  81. * v1.33: Use Date static method instead of instance, by @nnnoel
  82. * Fix bug with tooltips when multiple charts on a page, by @jpmbiz70
  83. * v1.34: Add disabled option to TimeSeries, by @TechGuard (#91)
  84. * Add nonRealtimeData option, by @annazhelt (#92, #93)
  85. * Add showIntermediateLabels option, by @annazhelt (#94)
  86. * Add displayDataFromPercentile option, by @annazhelt (#95)
  87. * Fix bug when hiding tooltip element, by @ralphwetzel (#96)
  88. * Support intermediate y-axis labels, by @beikeland (#99)
  89. * v1.35: Fix issue with responsive mode at high DPI, by @drewnoakes (#101)
  90. * v1.36: Add tooltipLabel to ITimeSeriesPresentationOptions.
  91. * If tooltipLabel is present, tooltipLabel displays inside tooltip
  92. * next to value, by @jackdesert (#102)
  93. * Fix bug rendering issue in series fill when using scroll backwards, by @olssonfredrik
  94. * Add title option, by @mesca
  95. * Fix data drop stoppage by rejecting NaNs in append(), by @timdrysdale
  96. */
  97. ;(function(exports) {
  98. // Date.now polyfill
  99. Date.now = Date.now || function() { return new Date().getTime(); };
  100. var Util = {
  101. extend: function() {
  102. arguments[0] = arguments[0] || {};
  103. for (var i = 1; i < arguments.length; i++)
  104. {
  105. for (var key in arguments[i])
  106. {
  107. if (arguments[i].hasOwnProperty(key))
  108. {
  109. if (typeof(arguments[i][key]) === 'object') {
  110. if (arguments[i][key] instanceof Array) {
  111. arguments[0][key] = arguments[i][key];
  112. } else {
  113. arguments[0][key] = Util.extend(arguments[0][key], arguments[i][key]);
  114. }
  115. } else {
  116. arguments[0][key] = arguments[i][key];
  117. }
  118. }
  119. }
  120. }
  121. return arguments[0];
  122. },
  123. binarySearch: function(data, value) {
  124. var low = 0,
  125. high = data.length;
  126. while (low < high) {
  127. var mid = (low + high) >> 1;
  128. if (value < data[mid][0])
  129. high = mid;
  130. else
  131. low = mid + 1;
  132. }
  133. return low;
  134. }
  135. };
  136. /**
  137. * Initialises a new <code>TimeSeries</code> with optional data options.
  138. *
  139. * Options are of the form (defaults shown):
  140. *
  141. * <pre>
  142. * {
  143. * resetBounds: true, // enables/disables automatic scaling of the y-axis
  144. * resetBoundsInterval: 3000 // the period between scaling calculations, in millis
  145. * }
  146. * </pre>
  147. *
  148. * Presentation options for TimeSeries are specified as an argument to <code>SmoothieChart.addTimeSeries</code>.
  149. *
  150. * @constructor
  151. */
  152. function TimeSeries(options) {
  153. this.options = Util.extend({}, TimeSeries.defaultOptions, options);
  154. this.disabled = false;
  155. this.clear();
  156. }
  157. TimeSeries.defaultOptions = {
  158. resetBoundsInterval: 3000,
  159. resetBounds: true
  160. };
  161. /**
  162. * Clears all data and state from this TimeSeries object.
  163. */
  164. TimeSeries.prototype.clear = function() {
  165. this.data = [];
  166. this.maxValue = Number.NaN; // The maximum value ever seen in this TimeSeries.
  167. this.minValue = Number.NaN; // The minimum value ever seen in this TimeSeries.
  168. };
  169. /**
  170. * Recalculate the min/max values for this <code>TimeSeries</code> object.
  171. *
  172. * This causes the graph to scale itself in the y-axis.
  173. */
  174. TimeSeries.prototype.resetBounds = function() {
  175. if (this.data.length) {
  176. // Walk through all data points, finding the min/max value
  177. this.maxValue = this.data[0][1];
  178. this.minValue = this.data[0][1];
  179. for (var i = 1; i < this.data.length; i++) {
  180. var value = this.data[i][1];
  181. if (value > this.maxValue) {
  182. this.maxValue = value;
  183. }
  184. if (value < this.minValue) {
  185. this.minValue = value;
  186. }
  187. }
  188. } else {
  189. // No data exists, so set min/max to NaN
  190. this.maxValue = Number.NaN;
  191. this.minValue = Number.NaN;
  192. }
  193. };
  194. /**
  195. * Adds a new data point to the <code>TimeSeries</code>, preserving chronological order.
  196. *
  197. * @param timestamp the position, in time, of this data point
  198. * @param value the value of this data point
  199. * @param sumRepeatedTimeStampValues if <code>timestamp</code> has an exact match in the series, this flag controls
  200. * whether it is replaced, or the values summed (defaults to false.)
  201. */
  202. TimeSeries.prototype.append = function(timestamp, value, sumRepeatedTimeStampValues) {
  203. // Reject NaN
  204. if (isNaN(timestamp) || isNaN(value)){
  205. return
  206. }
  207. // Rewind until we hit an older timestamp
  208. var i = this.data.length - 1;
  209. while (i >= 0 && this.data[i][0] > timestamp) {
  210. i--;
  211. }
  212. if (i === -1) {
  213. // This new item is the oldest data
  214. this.data.splice(0, 0, [timestamp, value]);
  215. } else if (this.data.length > 0 && this.data[i][0] === timestamp) {
  216. // Update existing values in the array
  217. if (sumRepeatedTimeStampValues) {
  218. // Sum this value into the existing 'bucket'
  219. this.data[i][1] += value;
  220. value = this.data[i][1];
  221. } else {
  222. // Replace the previous value
  223. this.data[i][1] = value;
  224. }
  225. } else if (i < this.data.length - 1) {
  226. // Splice into the correct position to keep timestamps in order
  227. this.data.splice(i + 1, 0, [timestamp, value]);
  228. } else {
  229. // Add to the end of the array
  230. this.data.push([timestamp, value]);
  231. }
  232. this.maxValue = isNaN(this.maxValue) ? value : Math.max(this.maxValue, value);
  233. this.minValue = isNaN(this.minValue) ? value : Math.min(this.minValue, value);
  234. };
  235. TimeSeries.prototype.dropOldData = function(oldestValidTime, maxDataSetLength) {
  236. // We must always keep one expired data point as we need this to draw the
  237. // line that comes into the chart from the left, but any points prior to that can be removed.
  238. var removeCount = 0;
  239. while (this.data.length - removeCount >= maxDataSetLength && this.data[removeCount + 1][0] < oldestValidTime) {
  240. removeCount++;
  241. }
  242. if (removeCount !== 0) {
  243. this.data.splice(0, removeCount);
  244. }
  245. };
  246. /**
  247. * Initialises a new <code>SmoothieChart</code>.
  248. *
  249. * Options are optional, and should be of the form below. Just specify the values you
  250. * need and the rest will be given sensible defaults as shown:
  251. *
  252. * <pre>
  253. * {
  254. * minValue: undefined, // specify to clamp the lower y-axis to a given value
  255. * maxValue: undefined, // specify to clamp the upper y-axis to a given value
  256. * maxValueScale: 1, // allows proportional padding to be added above the chart. for 10% padding, specify 1.1.
  257. * minValueScale: 1, // allows proportional padding to be added below the chart. for 10% padding, specify 1.1.
  258. * yRangeFunction: undefined, // function({min: , max: }) { return {min: , max: }; }
  259. * scaleSmoothing: 0.125, // controls the rate at which y-value zoom animation occurs
  260. * millisPerPixel: 20, // sets the speed at which the chart pans by
  261. * enableDpiScaling: true, // support rendering at different DPI depending on the device
  262. * yMinFormatter: function(min, precision) { // callback function that formats the min y value label
  263. * return parseFloat(min).toFixed(precision);
  264. * },
  265. * yMaxFormatter: function(max, precision) { // callback function that formats the max y value label
  266. * return parseFloat(max).toFixed(precision);
  267. * },
  268. * yIntermediateFormatter: function(intermediate, precision) { // callback function that formats the intermediate y value labels
  269. * return parseFloat(intermediate).toFixed(precision);
  270. * },
  271. * maxDataSetLength: 2,
  272. * interpolation: 'bezier' // one of 'bezier', 'linear', or 'step'
  273. * timestampFormatter: null, // optional function to format time stamps for bottom of chart
  274. * // you may use SmoothieChart.timeFormatter, or your own: function(date) { return ''; }
  275. * scrollBackwards: false, // reverse the scroll direction of the chart
  276. * horizontalLines: [], // [ { value: 0, color: '#ffffff', lineWidth: 1 } ]
  277. * grid:
  278. * {
  279. * fillStyle: '#000000', // the background colour of the chart
  280. * lineWidth: 1, // the pixel width of grid lines
  281. * strokeStyle: '#777777', // colour of grid lines
  282. * millisPerLine: 1000, // distance between vertical grid lines
  283. * sharpLines: false, // controls whether grid lines are 1px sharp, or softened
  284. * verticalSections: 2, // number of vertical sections marked out by horizontal grid lines
  285. * borderVisible: true // whether the grid lines trace the border of the chart or not
  286. * },
  287. * labels
  288. * {
  289. * disabled: false, // enables/disables labels showing the min/max values
  290. * fillStyle: '#ffffff', // colour for text of labels,
  291. * fontSize: 15,
  292. * fontFamily: 'sans-serif',
  293. * precision: 2,
  294. * showIntermediateLabels: false, // shows intermediate labels between min and max values along y axis
  295. * intermediateLabelSameAxis: true,
  296. * },
  297. * title
  298. * {
  299. * text: '', // the text to display on the left side of the chart
  300. * fillStyle: '#ffffff', // colour for text
  301. * fontSize: 15,
  302. * fontFamily: 'sans-serif',
  303. * verticalAlign: 'middle' // one of 'top', 'middle', or 'bottom'
  304. * },
  305. * tooltip: false // show tooltip when mouse is over the chart
  306. * tooltipLine: { // properties for a vertical line at the cursor position
  307. * lineWidth: 1,
  308. * strokeStyle: '#BBBBBB'
  309. * },
  310. * tooltipFormatter: SmoothieChart.tooltipFormatter, // formatter function for tooltip text
  311. * nonRealtimeData: false, // use time of latest data as current time
  312. * displayDataFromPercentile: 1, // display not latest data, but data from the given percentile
  313. * // useful when trying to see old data saved by setting a high value for maxDataSetLength
  314. * // should be a value between 0 and 1
  315. * responsive: false, // whether the chart should adapt to the size of the canvas
  316. * limitFPS: 0 // maximum frame rate the chart will render at, in FPS (zero means no limit)
  317. * }
  318. * </pre>
  319. *
  320. * @constructor
  321. */
  322. function SmoothieChart(options) {
  323. this.options = Util.extend({}, SmoothieChart.defaultChartOptions, options);
  324. this.seriesSet = [];
  325. this.currentValueRange = 1;
  326. this.currentVisMinValue = 0;
  327. this.lastRenderTimeMillis = 0;
  328. this.lastChartTimestamp = 0;
  329. this.mousemove = this.mousemove.bind(this);
  330. this.mouseout = this.mouseout.bind(this);
  331. }
  332. /** Formats the HTML string content of the tooltip. */
  333. SmoothieChart.tooltipFormatter = function (timestamp, data) {
  334. var timestampFormatter = this.options.timestampFormatter || SmoothieChart.timeFormatter,
  335. lines = [timestampFormatter(new Date(timestamp))],
  336. label;
  337. for (var i = 0; i < data.length; ++i) {
  338. label = data[i].series.options.tooltipLabel || ''
  339. if (label !== ''){
  340. label = label + ' ';
  341. }
  342. lines.push('<span style="color:' + data[i].series.options.strokeStyle + '">' +
  343. label +
  344. this.options.yMaxFormatter(data[i].value, this.options.labels.precision) + '</span>');
  345. }
  346. return lines.join('<br>');
  347. };
  348. SmoothieChart.defaultChartOptions = {
  349. millisPerPixel: 20,
  350. enableDpiScaling: true,
  351. yMinFormatter: function(min, precision) {
  352. return parseFloat(min).toFixed(precision);
  353. },
  354. yMaxFormatter: function(max, precision) {
  355. return parseFloat(max).toFixed(precision);
  356. },
  357. yIntermediateFormatter: function(intermediate, precision) {
  358. return parseFloat(intermediate).toFixed(precision);
  359. },
  360. maxValueScale: 1,
  361. minValueScale: 1,
  362. interpolation: 'bezier',
  363. scaleSmoothing: 0.125,
  364. maxDataSetLength: 2,
  365. scrollBackwards: false,
  366. displayDataFromPercentile: 1,
  367. grid: {
  368. fillStyle: '#000000',
  369. strokeStyle: '#777777',
  370. lineWidth: 1,
  371. sharpLines: false,
  372. millisPerLine: 1000,
  373. verticalSections: 2,
  374. borderVisible: true
  375. },
  376. labels: {
  377. fillStyle: '#ffffff',
  378. disabled: false,
  379. fontSize: 10,
  380. fontFamily: 'monospace',
  381. precision: 2,
  382. showIntermediateLabels: false,
  383. intermediateLabelSameAxis: true,
  384. },
  385. title: {
  386. text: '',
  387. fillStyle: '#ffffff',
  388. fontSize: 15,
  389. fontFamily: 'monospace',
  390. verticalAlign: 'middle'
  391. },
  392. horizontalLines: [],
  393. tooltip: false,
  394. tooltipLine: {
  395. lineWidth: 1,
  396. strokeStyle: '#BBBBBB'
  397. },
  398. tooltipFormatter: SmoothieChart.tooltipFormatter,
  399. nonRealtimeData: false,
  400. responsive: false,
  401. limitFPS: 0
  402. };
  403. // Based on http://inspirit.github.com/jsfeat/js/compatibility.js
  404. SmoothieChart.AnimateCompatibility = (function() {
  405. var requestAnimationFrame = function(callback, element) {
  406. var requestAnimationFrame =
  407. window.requestAnimationFrame ||
  408. window.webkitRequestAnimationFrame ||
  409. window.mozRequestAnimationFrame ||
  410. window.oRequestAnimationFrame ||
  411. window.msRequestAnimationFrame ||
  412. function(callback) {
  413. return window.setTimeout(function() {
  414. callback(Date.now());
  415. }, 16);
  416. };
  417. return requestAnimationFrame.call(window, callback, element);
  418. },
  419. cancelAnimationFrame = function(id) {
  420. var cancelAnimationFrame =
  421. window.cancelAnimationFrame ||
  422. function(id) {
  423. clearTimeout(id);
  424. };
  425. return cancelAnimationFrame.call(window, id);
  426. };
  427. return {
  428. requestAnimationFrame: requestAnimationFrame,
  429. cancelAnimationFrame: cancelAnimationFrame
  430. };
  431. })();
  432. SmoothieChart.defaultSeriesPresentationOptions = {
  433. lineWidth: 1,
  434. strokeStyle: '#ffffff'
  435. };
  436. /**
  437. * Adds a <code>TimeSeries</code> to this chart, with optional presentation options.
  438. *
  439. * Presentation options should be of the form (defaults shown):
  440. *
  441. * <pre>
  442. * {
  443. * lineWidth: 1,
  444. * strokeStyle: '#ffffff',
  445. * fillStyle: undefined,
  446. * tooltipLabel: undefined
  447. * }
  448. * </pre>
  449. */
  450. SmoothieChart.prototype.addTimeSeries = function(timeSeries, options) {
  451. this.seriesSet.push({timeSeries: timeSeries, options: Util.extend({}, SmoothieChart.defaultSeriesPresentationOptions, options)});
  452. if (timeSeries.options.resetBounds && timeSeries.options.resetBoundsInterval > 0) {
  453. timeSeries.resetBoundsTimerId = setInterval(
  454. function() {
  455. timeSeries.resetBounds();
  456. },
  457. timeSeries.options.resetBoundsInterval
  458. );
  459. }
  460. };
  461. /**
  462. * Removes the specified <code>TimeSeries</code> from the chart.
  463. */
  464. SmoothieChart.prototype.removeTimeSeries = function(timeSeries) {
  465. // Find the correct timeseries to remove, and remove it
  466. var numSeries = this.seriesSet.length;
  467. for (var i = 0; i < numSeries; i++) {
  468. if (this.seriesSet[i].timeSeries === timeSeries) {
  469. this.seriesSet.splice(i, 1);
  470. break;
  471. }
  472. }
  473. // If a timer was operating for that timeseries, remove it
  474. if (timeSeries.resetBoundsTimerId) {
  475. // Stop resetting the bounds, if we were
  476. clearInterval(timeSeries.resetBoundsTimerId);
  477. }
  478. };
  479. /**
  480. * Gets render options for the specified <code>TimeSeries</code>.
  481. *
  482. * As you may use a single <code>TimeSeries</code> in multiple charts with different formatting in each usage,
  483. * these settings are stored in the chart.
  484. */
  485. SmoothieChart.prototype.getTimeSeriesOptions = function(timeSeries) {
  486. // Find the correct timeseries to remove, and remove it
  487. var numSeries = this.seriesSet.length;
  488. for (var i = 0; i < numSeries; i++) {
  489. if (this.seriesSet[i].timeSeries === timeSeries) {
  490. return this.seriesSet[i].options;
  491. }
  492. }
  493. };
  494. /**
  495. * Brings the specified <code>TimeSeries</code> to the top of the chart. It will be rendered last.
  496. */
  497. SmoothieChart.prototype.bringToFront = function(timeSeries) {
  498. // Find the correct timeseries to remove, and remove it
  499. var numSeries = this.seriesSet.length;
  500. for (var i = 0; i < numSeries; i++) {
  501. if (this.seriesSet[i].timeSeries === timeSeries) {
  502. var set = this.seriesSet.splice(i, 1);
  503. this.seriesSet.push(set[0]);
  504. break;
  505. }
  506. }
  507. };
  508. /**
  509. * Instructs the <code>SmoothieChart</code> to start rendering to the provided canvas, with specified delay.
  510. *
  511. * @param canvas the target canvas element
  512. * @param delayMillis an amount of time to wait before a data point is shown. This can prevent the end of the series
  513. * from appearing on screen, with new values flashing into view, at the expense of some latency.
  514. */
  515. SmoothieChart.prototype.streamTo = function(canvas, delayMillis) {
  516. this.canvas = canvas;
  517. this.delay = delayMillis;
  518. this.start();
  519. };
  520. SmoothieChart.prototype.getTooltipEl = function () {
  521. // Create the tool tip element lazily
  522. if (!this.tooltipEl) {
  523. this.tooltipEl = document.createElement('div');
  524. this.tooltipEl.className = 'smoothie-chart-tooltip';
  525. this.tooltipEl.style.position = 'absolute';
  526. this.tooltipEl.style.display = 'none';
  527. document.body.appendChild(this.tooltipEl);
  528. }
  529. return this.tooltipEl;
  530. };
  531. SmoothieChart.prototype.updateTooltip = function () {
  532. if(!this.options.tooltip){
  533. return;
  534. }
  535. var el = this.getTooltipEl();
  536. if (!this.mouseover || !this.options.tooltip) {
  537. el.style.display = 'none';
  538. return;
  539. }
  540. var time = this.lastChartTimestamp;
  541. // x pixel to time
  542. var t = this.options.scrollBackwards
  543. ? time - this.mouseX * this.options.millisPerPixel
  544. : time - (this.canvas.offsetWidth - this.mouseX) * this.options.millisPerPixel;
  545. var data = [];
  546. // For each data set...
  547. for (var d = 0; d < this.seriesSet.length; d++) {
  548. var timeSeries = this.seriesSet[d].timeSeries;
  549. if (timeSeries.disabled) {
  550. continue;
  551. }
  552. // find datapoint closest to time 't'
  553. var closeIdx = Util.binarySearch(timeSeries.data, t);
  554. if (closeIdx > 0 && closeIdx < timeSeries.data.length) {
  555. data.push({ series: this.seriesSet[d], index: closeIdx, value: timeSeries.data[closeIdx][1] });
  556. }
  557. }
  558. if (data.length) {
  559. el.innerHTML = this.options.tooltipFormatter.call(this, t, data);
  560. el.style.display = 'block';
  561. } else {
  562. el.style.display = 'none';
  563. }
  564. };
  565. SmoothieChart.prototype.mousemove = function (evt) {
  566. this.mouseover = true;
  567. this.mouseX = evt.offsetX;
  568. this.mouseY = evt.offsetY;
  569. this.mousePageX = evt.pageX;
  570. this.mousePageY = evt.pageY;
  571. if(!this.options.tooltip){
  572. return;
  573. }
  574. var el = this.getTooltipEl();
  575. el.style.top = Math.round(this.mousePageY) + 'px';
  576. el.style.left = Math.round(this.mousePageX) + 'px';
  577. this.updateTooltip();
  578. };
  579. SmoothieChart.prototype.mouseout = function () {
  580. this.mouseover = false;
  581. this.mouseX = this.mouseY = -1;
  582. if (this.tooltipEl)
  583. this.tooltipEl.style.display = 'none';
  584. };
  585. /**
  586. * Make sure the canvas has the optimal resolution for the device's pixel ratio.
  587. */
  588. SmoothieChart.prototype.resize = function () {
  589. var dpr = !this.options.enableDpiScaling || !window ? 1 : window.devicePixelRatio,
  590. width, height;
  591. if (this.options.responsive) {
  592. // Newer behaviour: Use the canvas's size in the layout, and set the internal
  593. // resolution according to that size and the device pixel ratio (eg: high DPI)
  594. width = this.canvas.offsetWidth;
  595. height = this.canvas.offsetHeight;
  596. if (width !== this.lastWidth) {
  597. this.lastWidth = width;
  598. this.canvas.setAttribute('width', (Math.floor(width * dpr)).toString());
  599. this.canvas.getContext('2d').scale(dpr, dpr);
  600. }
  601. if (height !== this.lastHeight) {
  602. this.lastHeight = height;
  603. this.canvas.setAttribute('height', (Math.floor(height * dpr)).toString());
  604. this.canvas.getContext('2d').scale(dpr, dpr);
  605. }
  606. } else if (dpr !== 1) {
  607. // Older behaviour: use the canvas's inner dimensions and scale the element's size
  608. // according to that size and the device pixel ratio (eg: high DPI)
  609. width = parseInt(this.canvas.getAttribute('width'));
  610. height = parseInt(this.canvas.getAttribute('height'));
  611. if (!this.originalWidth || (Math.floor(this.originalWidth * dpr) !== width)) {
  612. this.originalWidth = width;
  613. this.canvas.setAttribute('width', (Math.floor(width * dpr)).toString());
  614. this.canvas.style.width = width + 'px';
  615. this.canvas.getContext('2d').scale(dpr, dpr);
  616. }
  617. if (!this.originalHeight || (Math.floor(this.originalHeight * dpr) !== height)) {
  618. this.originalHeight = height;
  619. this.canvas.setAttribute('height', (Math.floor(height * dpr)).toString());
  620. this.canvas.style.height = height + 'px';
  621. this.canvas.getContext('2d').scale(dpr, dpr);
  622. }
  623. }
  624. };
  625. /**
  626. * Starts the animation of this chart.
  627. */
  628. SmoothieChart.prototype.start = function() {
  629. if (this.frame) {
  630. // We're already running, so just return
  631. return;
  632. }
  633. this.canvas.addEventListener('mousemove', this.mousemove);
  634. this.canvas.addEventListener('mouseout', this.mouseout);
  635. // Renders a frame, and queues the next frame for later rendering
  636. var animate = function() {
  637. this.frame = SmoothieChart.AnimateCompatibility.requestAnimationFrame(function() {
  638. if(this.options.nonRealtimeData){
  639. var dateZero = new Date(0);
  640. // find the data point with the latest timestamp
  641. var maxTimeStamp = this.seriesSet.reduce(function(max, series){
  642. var dataSet = series.timeSeries.data;
  643. var indexToCheck = Math.round(this.options.displayDataFromPercentile * dataSet.length) - 1;
  644. indexToCheck = indexToCheck >= 0 ? indexToCheck : 0;
  645. indexToCheck = indexToCheck <= dataSet.length -1 ? indexToCheck : dataSet.length -1;
  646. if(dataSet && dataSet.length > 0)
  647. {
  648. // timestamp corresponds to element 0 of the data point
  649. var lastDataTimeStamp = dataSet[indexToCheck][0];
  650. max = max > lastDataTimeStamp ? max : lastDataTimeStamp;
  651. }
  652. return max;
  653. }.bind(this), dateZero);
  654. // use the max timestamp as current time
  655. this.render(this.canvas, maxTimeStamp > dateZero ? maxTimeStamp : null);
  656. } else {
  657. this.render();
  658. }
  659. animate();
  660. }.bind(this));
  661. }.bind(this);
  662. animate();
  663. };
  664. /**
  665. * Stops the animation of this chart.
  666. */
  667. SmoothieChart.prototype.stop = function() {
  668. if (this.frame) {
  669. SmoothieChart.AnimateCompatibility.cancelAnimationFrame(this.frame);
  670. delete this.frame;
  671. this.canvas.removeEventListener('mousemove', this.mousemove);
  672. this.canvas.removeEventListener('mouseout', this.mouseout);
  673. }
  674. };
  675. SmoothieChart.prototype.updateValueRange = function() {
  676. // Calculate the current scale of the chart, from all time series.
  677. var chartOptions = this.options,
  678. chartMaxValue = Number.NaN,
  679. chartMinValue = Number.NaN;
  680. for (var d = 0; d < this.seriesSet.length; d++) {
  681. // TODO(ndunn): We could calculate / track these values as they stream in.
  682. var timeSeries = this.seriesSet[d].timeSeries;
  683. if (timeSeries.disabled) {
  684. continue;
  685. }
  686. if (!isNaN(timeSeries.maxValue)) {
  687. chartMaxValue = !isNaN(chartMaxValue) ? Math.max(chartMaxValue, timeSeries.maxValue) : timeSeries.maxValue;
  688. }
  689. if (!isNaN(timeSeries.minValue)) {
  690. chartMinValue = !isNaN(chartMinValue) ? Math.min(chartMinValue, timeSeries.minValue) : timeSeries.minValue;
  691. }
  692. }
  693. // Scale the chartMaxValue to add padding at the top if required
  694. if (chartOptions.maxValue != null) {
  695. chartMaxValue = chartOptions.maxValue;
  696. } else {
  697. chartMaxValue *= chartOptions.maxValueScale;
  698. }
  699. // Set the minimum if we've specified one
  700. if (chartOptions.minValue != null) {
  701. chartMinValue = chartOptions.minValue;
  702. } else {
  703. chartMinValue -= Math.abs(chartMinValue * chartOptions.minValueScale - chartMinValue);
  704. }
  705. // If a custom range function is set, call it
  706. if (this.options.yRangeFunction) {
  707. var range = this.options.yRangeFunction({min: chartMinValue, max: chartMaxValue});
  708. chartMinValue = range.min;
  709. chartMaxValue = range.max;
  710. }
  711. if (!isNaN(chartMaxValue) && !isNaN(chartMinValue)) {
  712. var targetValueRange = chartMaxValue - chartMinValue;
  713. var valueRangeDiff = (targetValueRange - this.currentValueRange);
  714. var minValueDiff = (chartMinValue - this.currentVisMinValue);
  715. this.isAnimatingScale = Math.abs(valueRangeDiff) > 0.1 || Math.abs(minValueDiff) > 0.1;
  716. this.currentValueRange += chartOptions.scaleSmoothing * valueRangeDiff;
  717. this.currentVisMinValue += chartOptions.scaleSmoothing * minValueDiff;
  718. }
  719. this.valueRange = { min: chartMinValue, max: chartMaxValue };
  720. };
  721. SmoothieChart.prototype.render = function(canvas, time) {
  722. var nowMillis = Date.now();
  723. // Respect any frame rate limit.
  724. if (this.options.limitFPS > 0 && nowMillis - this.lastRenderTimeMillis < (1000/this.options.limitFPS))
  725. return;
  726. if (!this.isAnimatingScale) {
  727. // We're not animating. We can use the last render time and the scroll speed to work out whether
  728. // we actually need to paint anything yet. If not, we can return immediately.
  729. // Render at least every 1/6th of a second. The canvas may be resized, which there is
  730. // no reliable way to detect.
  731. var maxIdleMillis = Math.min(1000/6, this.options.millisPerPixel);
  732. if (nowMillis - this.lastRenderTimeMillis < maxIdleMillis) {
  733. return;
  734. }
  735. }
  736. this.resize();
  737. this.updateTooltip();
  738. this.lastRenderTimeMillis = nowMillis;
  739. canvas = canvas || this.canvas;
  740. time = time || nowMillis - (this.delay || 0);
  741. // Round time down to pixel granularity, so motion appears smoother.
  742. time -= time % this.options.millisPerPixel;
  743. this.lastChartTimestamp = time;
  744. var context = canvas.getContext('2d'),
  745. chartOptions = this.options,
  746. dimensions = { top: 0, left: 0, width: canvas.clientWidth, height: canvas.clientHeight },
  747. // Calculate the threshold time for the oldest data points.
  748. oldestValidTime = time - (dimensions.width * chartOptions.millisPerPixel),
  749. valueToYPixel = function(value) {
  750. var offset = value - this.currentVisMinValue;
  751. return this.currentValueRange === 0
  752. ? dimensions.height
  753. : dimensions.height - (Math.round((offset / this.currentValueRange) * dimensions.height));
  754. }.bind(this),
  755. timeToXPixel = function(t) {
  756. if(chartOptions.scrollBackwards) {
  757. return Math.round((time - t) / chartOptions.millisPerPixel);
  758. }
  759. return Math.round(dimensions.width - ((time - t) / chartOptions.millisPerPixel));
  760. };
  761. this.updateValueRange();
  762. context.font = chartOptions.labels.fontSize + 'px ' + chartOptions.labels.fontFamily;
  763. // Save the state of the canvas context, any transformations applied in this method
  764. // will get removed from the stack at the end of this method when .restore() is called.
  765. context.save();
  766. // Move the origin.
  767. context.translate(dimensions.left, dimensions.top);
  768. // Create a clipped rectangle - anything we draw will be constrained to this rectangle.
  769. // This prevents the occasional pixels from curves near the edges overrunning and creating
  770. // screen cheese (that phrase should need no explanation).
  771. context.beginPath();
  772. context.rect(0, 0, dimensions.width, dimensions.height);
  773. context.clip();
  774. // Clear the working area.
  775. context.save();
  776. context.fillStyle = chartOptions.grid.fillStyle;
  777. context.clearRect(0, 0, dimensions.width, dimensions.height);
  778. context.fillRect(0, 0, dimensions.width, dimensions.height);
  779. context.restore();
  780. // Grid lines...
  781. context.save();
  782. context.lineWidth = chartOptions.grid.lineWidth;
  783. context.strokeStyle = chartOptions.grid.strokeStyle;
  784. // Vertical (time) dividers.
  785. if (chartOptions.grid.millisPerLine > 0) {
  786. context.beginPath();
  787. for (var t = time - (time % chartOptions.grid.millisPerLine);
  788. t >= oldestValidTime;
  789. t -= chartOptions.grid.millisPerLine) {
  790. var gx = timeToXPixel(t);
  791. if (chartOptions.grid.sharpLines) {
  792. gx -= 0.5;
  793. }
  794. context.moveTo(gx, 0);
  795. context.lineTo(gx, dimensions.height);
  796. }
  797. context.stroke();
  798. context.closePath();
  799. }
  800. // Horizontal (value) dividers.
  801. for (var v = 1; v < chartOptions.grid.verticalSections; v++) {
  802. var gy = Math.round(v * dimensions.height / chartOptions.grid.verticalSections);
  803. if (chartOptions.grid.sharpLines) {
  804. gy -= 0.5;
  805. }
  806. context.beginPath();
  807. context.moveTo(0, gy);
  808. context.lineTo(dimensions.width, gy);
  809. context.stroke();
  810. context.closePath();
  811. }
  812. // Bounding rectangle.
  813. if (chartOptions.grid.borderVisible) {
  814. context.beginPath();
  815. context.strokeRect(0, 0, dimensions.width, dimensions.height);
  816. context.closePath();
  817. }
  818. context.restore();
  819. // Draw any horizontal lines...
  820. if (chartOptions.horizontalLines && chartOptions.horizontalLines.length) {
  821. for (var hl = 0; hl < chartOptions.horizontalLines.length; hl++) {
  822. var line = chartOptions.horizontalLines[hl],
  823. hly = Math.round(valueToYPixel(line.value)) - 0.5;
  824. context.strokeStyle = line.color || '#ffffff';
  825. context.lineWidth = line.lineWidth || 1;
  826. context.beginPath();
  827. context.moveTo(0, hly);
  828. context.lineTo(dimensions.width, hly);
  829. context.stroke();
  830. context.closePath();
  831. }
  832. }
  833. // For each data set...
  834. for (var d = 0; d < this.seriesSet.length; d++) {
  835. context.save();
  836. var timeSeries = this.seriesSet[d].timeSeries;
  837. if (timeSeries.disabled) {
  838. continue;
  839. }
  840. var dataSet = timeSeries.data,
  841. seriesOptions = this.seriesSet[d].options;
  842. // Delete old data that's moved off the left of the chart.
  843. timeSeries.dropOldData(oldestValidTime, chartOptions.maxDataSetLength);
  844. // Set style for this dataSet.
  845. context.lineWidth = seriesOptions.lineWidth;
  846. context.strokeStyle = seriesOptions.strokeStyle;
  847. // Draw the line...
  848. context.beginPath();
  849. // Retain lastX, lastY for calculating the control points of bezier curves.
  850. var firstX = 0, firstY = 0, lastX = 0, lastY = 0;
  851. for (var i = 0; i < dataSet.length && dataSet.length !== 1; i++) {
  852. var x = timeToXPixel(dataSet[i][0]),
  853. y = valueToYPixel(dataSet[i][1]);
  854. if (i === 0) {
  855. firstX = x;
  856. firstY = y;
  857. context.moveTo(x, y);
  858. } else {
  859. switch (chartOptions.interpolation) {
  860. case "linear":
  861. case "line": {
  862. context.lineTo(x,y);
  863. break;
  864. }
  865. case "bezier":
  866. default: {
  867. // Great explanation of Bezier curves: http://en.wikipedia.org/wiki/Bezier_curve#Quadratic_curves
  868. //
  869. // Assuming A was the last point in the line plotted and B is the new point,
  870. // we draw a curve with control points P and Q as below.
  871. //
  872. // A---P
  873. // |
  874. // |
  875. // |
  876. // Q---B
  877. //
  878. // Importantly, A and P are at the same y coordinate, as are B and Q. This is
  879. // so adjacent curves appear to flow as one.
  880. //
  881. context.bezierCurveTo( // startPoint (A) is implicit from last iteration of loop
  882. Math.round((lastX + x) / 2), lastY, // controlPoint1 (P)
  883. Math.round((lastX + x)) / 2, y, // controlPoint2 (Q)
  884. x, y); // endPoint (B)
  885. break;
  886. }
  887. case "step": {
  888. context.lineTo(x,lastY);
  889. context.lineTo(x,y);
  890. break;
  891. }
  892. }
  893. }
  894. lastX = x; lastY = y;
  895. }
  896. if (dataSet.length > 1) {
  897. if (seriesOptions.fillStyle) {
  898. // Close up the fill region.
  899. if (chartOptions.scrollBackwards) {
  900. context.lineTo(lastX, dimensions.height + seriesOptions.lineWidth);
  901. context.lineTo(firstX, dimensions.height + seriesOptions.lineWidth);
  902. context.lineTo(firstX, firstY);
  903. } else {
  904. context.lineTo(dimensions.width + seriesOptions.lineWidth + 1, lastY);
  905. context.lineTo(dimensions.width + seriesOptions.lineWidth + 1, dimensions.height + seriesOptions.lineWidth + 1);
  906. context.lineTo(firstX, dimensions.height + seriesOptions.lineWidth);
  907. }
  908. context.fillStyle = seriesOptions.fillStyle;
  909. context.fill();
  910. }
  911. if (seriesOptions.strokeStyle && seriesOptions.strokeStyle !== 'none') {
  912. context.stroke();
  913. }
  914. context.closePath();
  915. }
  916. context.restore();
  917. }
  918. if (chartOptions.tooltip && this.mouseX >= 0) {
  919. // Draw vertical bar to show tooltip position
  920. context.lineWidth = chartOptions.tooltipLine.lineWidth;
  921. context.strokeStyle = chartOptions.tooltipLine.strokeStyle;
  922. context.beginPath();
  923. context.moveTo(this.mouseX, 0);
  924. context.lineTo(this.mouseX, dimensions.height);
  925. context.closePath();
  926. context.stroke();
  927. this.updateTooltip();
  928. }
  929. // Draw the axis values on the chart.
  930. if (!chartOptions.labels.disabled && !isNaN(this.valueRange.min) && !isNaN(this.valueRange.max)) {
  931. var maxValueString = chartOptions.yMaxFormatter(this.valueRange.max, chartOptions.labels.precision),
  932. minValueString = chartOptions.yMinFormatter(this.valueRange.min, chartOptions.labels.precision),
  933. maxLabelPos = chartOptions.scrollBackwards ? 0 : dimensions.width - context.measureText(maxValueString).width - 2,
  934. minLabelPos = chartOptions.scrollBackwards ? 0 : dimensions.width - context.measureText(minValueString).width - 2;
  935. context.fillStyle = chartOptions.labels.fillStyle;
  936. context.fillText(maxValueString, maxLabelPos, chartOptions.labels.fontSize);
  937. context.fillText(minValueString, minLabelPos, dimensions.height - 2);
  938. }
  939. // Display intermediate y axis labels along y-axis to the left of the chart
  940. if ( chartOptions.labels.showIntermediateLabels
  941. && !isNaN(this.valueRange.min) && !isNaN(this.valueRange.max)
  942. && chartOptions.grid.verticalSections > 0) {
  943. // show a label above every vertical section divider
  944. var step = (this.valueRange.max - this.valueRange.min) / chartOptions.grid.verticalSections;
  945. var stepPixels = dimensions.height / chartOptions.grid.verticalSections;
  946. for (var v = 1; v < chartOptions.grid.verticalSections; v++) {
  947. var gy = dimensions.height - Math.round(v * stepPixels);
  948. if (chartOptions.grid.sharpLines) {
  949. gy -= 0.5;
  950. }
  951. var yValue = chartOptions.yIntermediateFormatter(this.valueRange.min + (v * step), chartOptions.labels.precision);
  952. //left of right axis?
  953. intermediateLabelPos =
  954. chartOptions.labels.intermediateLabelSameAxis
  955. ? (chartOptions.scrollBackwards ? 0 : dimensions.width - context.measureText(yValue).width - 2)
  956. : (chartOptions.scrollBackwards ? dimensions.width - context.measureText(yValue).width - 2 : 0);
  957. context.fillText(yValue, intermediateLabelPos, gy - chartOptions.grid.lineWidth);
  958. }
  959. }
  960. // Display timestamps along x-axis at the bottom of the chart.
  961. if (chartOptions.timestampFormatter && chartOptions.grid.millisPerLine > 0) {
  962. var textUntilX = chartOptions.scrollBackwards
  963. ? context.measureText(minValueString).width
  964. : dimensions.width - context.measureText(minValueString).width + 4;
  965. for (var t = time - (time % chartOptions.grid.millisPerLine);
  966. t >= oldestValidTime;
  967. t -= chartOptions.grid.millisPerLine) {
  968. var gx = timeToXPixel(t);
  969. // Only draw the timestamp if it won't overlap with the previously drawn one.
  970. if ((!chartOptions.scrollBackwards && gx < textUntilX) || (chartOptions.scrollBackwards && gx > textUntilX)) {
  971. // Formats the timestamp based on user specified formatting function
  972. // SmoothieChart.timeFormatter function above is one such formatting option
  973. var tx = new Date(t),
  974. ts = chartOptions.timestampFormatter(tx),
  975. tsWidth = context.measureText(ts).width;
  976. textUntilX = chartOptions.scrollBackwards
  977. ? gx + tsWidth + 2
  978. : gx - tsWidth - 2;
  979. context.fillStyle = chartOptions.labels.fillStyle;
  980. if(chartOptions.scrollBackwards) {
  981. context.fillText(ts, gx, dimensions.height - 2);
  982. } else {
  983. context.fillText(ts, gx - tsWidth, dimensions.height - 2);
  984. }
  985. }
  986. }
  987. }
  988. // Display title.
  989. if (chartOptions.title.text !== '') {
  990. context.font = chartOptions.title.fontSize + 'px ' + chartOptions.title.fontFamily;
  991. var titleXPos = chartOptions.scrollBackwards ? dimensions.width - context.measureText(chartOptions.title.text).width - 2 : 2;
  992. if (chartOptions.title.verticalAlign == 'bottom') {
  993. context.textBaseline = 'bottom';
  994. var titleYPos = dimensions.height;
  995. } else if (chartOptions.title.verticalAlign == 'middle') {
  996. context.textBaseline = 'middle';
  997. var titleYPos = dimensions.height / 2;
  998. } else {
  999. context.textBaseline = 'top';
  1000. var titleYPos = 0;
  1001. }
  1002. context.fillStyle = chartOptions.title.fillStyle;
  1003. context.fillText(chartOptions.title.text, titleXPos, titleYPos);
  1004. }
  1005. context.restore(); // See .save() above.
  1006. };
  1007. // Sample timestamp formatting function
  1008. SmoothieChart.timeFormatter = function(date) {
  1009. function pad2(number) { return (number < 10 ? '0' : '') + number }
  1010. return pad2(date.getHours()) + ':' + pad2(date.getMinutes()) + ':' + pad2(date.getSeconds());
  1011. };
  1012. exports.TimeSeries = TimeSeries;
  1013. exports.SmoothieChart = SmoothieChart;
  1014. })(typeof exports === 'undefined' ? this : exports);